Difference between revisions of "S2 Cookbook: Dates"

From Dreamwidth Notes
Jump to: navigation, search
(Getting the current date or time)
 
Line 11: Line 11:
 
# just the date by casting  
 
# just the date by casting  
 
var Date current_date = journal_current_datetime() as Date;
 
var Date current_date = journal_current_datetime() as Date;
 +
</syntaxhighlight>
 +
 +
Alternatively, use the <tt>local_time</tt> or <tt>time</tt> variables inside of the current <tt>Page</tt>:
 +
 +
<syntaxhighlight lang="s2">
 +
# Get the current page
 +
Page p = get_page();
 +
# Get the time according to the journal's timezone
 +
var DateTime local_datetime = p->local_time();
 +
# Get the GMT time
 +
var DateTime gmt_datetime = p->time():
 
</syntaxhighlight>
 
</syntaxhighlight>
  

Latest revision as of 08:42, 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;

Alternatively, use the local_time or time variables inside of the current Page:

# Get the current page
Page p = get_page();
# Get the time according to the journal's timezone
var DateTime local_datetime = p->local_time();
# Get the GMT time
var DateTime gmt_datetime = p->time():

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