Difference between revisions of "S2 Cookbook: Dates"

From Dreamwidth Notes
Jump to: navigation, search
m
Line 12: Line 12:
 
var Date current_date = journal_current_datetime() as Date;
 
var Date current_date = journal_current_datetime() as Date;
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
== Printing out the current date or time ==
  
 
== Getting the day of the week ==
 
== Getting the day of the week ==
Line 37: Line 39:
  
 
  Possible weekday labels: Thursday Thu T
 
  Possible weekday labels: Thursday Thu T
 +
 +
== Linking to a journal's archive pages for a given day ==
 +
 +
== Comparing two dates to see which is more recent ==
  
 
[[Category: S2 Cookbook]]
 
[[Category: S2 Cookbook]]

Revision as of 08:22, 17 June 2010

The two classes involved with dates are Date, which represents a date, and DateTime, which represents both a date and time.

Getting the current date or time

The function you use for this is journal_current_datetime(), which returns the current DateTime in the timezone of the journal being viewed.

# Get both the date and the time
var DateTime current_datetime = journal_current_datetime();
# Because DateTime is a child class of Date, you can also get
# just the date by casting 
var Date current_date = journal_current_datetime() as Date;

Printing out the current date or time

Getting the day of the week

The Date and DateTime classes both have a function called day_of_week. It returns an integer between 1 and 7, where Sunday starts at 1 and Saturday ends at 7. You can then get the name of the day from one of several properties:

  • lang_dayname_long -- Array containing the long name of the day: Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
  • lang_dayname_short -- Array containing day abbreviations: Sun, Mon, Tue, Wed, Thu, Fri, Sat
  • lang_dayname_shorter -- Array containing day letters: S, M, T, W, T, F, S
# We'll use the current time as our DateTime class
var DateTime current_datetime = journal_current_datetime();
# Get our day of the week number
var int weekday = $current_datetime->day_of_week();
# Get all of the possible week day labels, using our day of the week number
var string full_dayname = $*lang_dayname_long[$weekday];
var string short_dayname = $*lang_dayname_short[$weekday];
var string letter_dayname = $*lang_dayname_shorter[$weekday];
# Example printing
print "Possible weekday labels: $full_dayname $short_dayname $letter_dayname";

If it was a Thursday, the above would print out:

Possible weekday labels: Thursday Thu T

Linking to a journal's archive pages for a given day

Comparing two dates to see which is more recent