Date Formatting with YUI – Part I
With the release of YUI 2.6.0, we’ve added a date formatting component as part of the DataSource utility. This date formatter brings the full power of strftime to Javascript. In a series of blog posts, we’ll go through examples of using the date formatter to best effect.
To start off, we first need to include the DataSource utility:
<script type=”text/javascript” src=”http://yui.yahooapis.com/2.6.0/build/yahoo/yahoo-min.js”></script> <script type=”text/javascript” src=”http://yui.yahooapis.com/2.6.0/build/event/event-min.js”></script> <script type=”text/javascript” src=”http://yui.yahooapis.com/2.6.0/build/datasource/datasource-min.js”></script>
Now let’s see it in action straight away:
<script type="text/javascript">
alert(YAHOO.util.Date.format(new Date(), {format: "%Y-%m-%d %T \n %B, %A"}));
</script>
Let’s try something more interactive. We’ll throw in some markup to read in a format and display the output:
<form> <label>Enter a format: <input type="text" name="date-format" id="date-format" value=""></label><br> <input type="submit" value="Show Me!" id="btnShow"> </form> <div id="messages"> </div>
Finally, we write some JavaScript to read in a format from the textbox and write out the formatted date to the target div:
<script type="text/javascript">
YAHOO.namespace("YAHOO.example.DateFormatter");
YAHOO.example.DateFormatter.formatDate = function(e)
{
YAHOO.util.Event.stopEvent(e);
var el = document.getElementById("date-format");
if(el && el.value)
{
var messages = document.getElementById("messages");
var date_str = YAHOO.util.Date.format(new Date(), { format: el.value });
messages.innerHTML = "<em>" + date_str + "</em>";
}
};
YAHOO.util.Event.addListener("btnShow", "click", YAHOO.example.DateFormatter.formatDate);
</script>
Put it all together, and we have a working example. Try some formats yourself, as defined by the strftime library. You can combine multiple formats and add your own text as well.
Yes, you can also put some HTML in there.
The full list of supported formats is:
- %a
- Abbreviated weekday name according to the current locale
- %A
- Full weekday name according to the current locale
- %b
- Abbreviated month name according to the current locale
- %B
- Full month name according to the current locale
- %c
- Preferred date and time representation for the current locale
- %C
- Century number (the year divided by 100 and truncated to an integer, range 00 to 99)
- %d
- Day of the month as a decimal number (range 01 to 31)
- %D
- Same as %m/%d/%y
- %e
- Day of the month as a decimal number, a single digit is preceded by a space (range ‘1′ to ‘31′)
- %F
- Same as %Y-%m-%d (ISO 8601 date format)
- %g
- Like %G, but without the century
- %G
- the 4-digit year corresponding to the ISO week number
- %h
- Same as %b
- %H
- Hour as a decimal number using a 24-hour clock (range 00 to 23)
- %I
- Hour as a decimal number using a 12-hour clock (range 01 to 12)
- %j
- Day of the year as a decimal number (range 001 to 366)
- %k
- Hour as a decimal number using a 24-hour clock (range 0 to 23); single digits are preceded by a blank. (See also %H.)
- %l
- Hour as a decimal number using a 12-hour clock (range 1 to 12); single digits are preceded by a blank. (See also %I.)
- %m
- Month as a decimal number (range 01 to 12)
- %M
- Minute as a decimal number
- %n
- Newline character (as good as whitespace in HTML)
- %p
- Either ‘AM’ or ‘PM’ according to the given time value, or the corresponding strings for the current locale
- %P
- Like %p, but lower case
- %r
- Time in a.m. and p.m. notation equivalent to %I:%M:%S %p
- %R
- Time in 24 hour notation equivalent to %H:%M
- %s
- Number of seconds since the Epoch, ie, since 1970-01-01 00:00:00 UTC
- %S
- Second as a decimal number
- %t
- Tab character
- %T
- Current time, equivalent to %H:%M:%S
- %u
- Weekday as a decimal number [1,7], with 1 representing Monday
- %U
- Week number of the current year as a decimal number, starting with
the first Sunday as the first day of the first week - %V
- The ISO 8601:1988 week number of the current year as a decimal number,
range 01 to 53, where week 1 is the first week that has at least 4 days
in the current year, and with Monday as the first day of the week. - %w
- Day of the week as a decimal, Sunday being 0
- %W
- Week number of the current year as a decimal number, starting with the
first Monday as the first day of the first week - %x
- Preferred date representation for the current locale without the time
- %X
- Preferred time representation for the current locale without the date
- %y
- Year as a decimal number without a century (range 00 to 99)
- %Y
- Year as a decimal number including the century
- %z
- Numerical time zone representation
- %Z
- Time zone name or abbreviation
- %%
- A literal ‘%’ character
We’ve seen how to use the date formatter to print out the current date in different formats. The current date, however, is interesting only some of the time. Most of the time we have dates from other sources that we need formatted.
The YAHOO.util.Date.format method accepts three parameters. Only the first of these — the date to be formatted — is required. We can pass in a JavaScript Date object that refers to any date, within JavaScript’s acceptable range, and have it formatted to our needs.
Let’s give it a try:
<script type="text/javascript">
var d = new Date("2009/01/15");
alert(YAHOO.util.Date.format(d, {format: "%Y-%m-%d %T %Z"}));
</script>
We can pass in the current date, time, and timezone and do it all in the call to format itself:
<script type="text/javascript">
alert(YAHOO.util.Date.format(new Date("2009/01/15 10:12:45 UTC"), {format: "%Y-%m-%d %T %Z"}));
</script>
Notice how the date is always displayed in the local (browser) timezone, even if we initialise it to UTC. Unfortunately, at this time the date formatter cannot display dates in other timezones. However, future versions may add the ability to display dates in UTC in addition to local time.
We can also enter a Unix timestamp in milliseconds, and have that show up as a formatted date:
<script type="text/javascript">
alert(YAHOO.util.Date.format(new Date(1234567891011), {format: "%Y-%m-%d %T %Z"}));
</script>
You can pass in a date in any of the formats supported by the JavaScript Date constructor. If you want to go further than that though, help is at hand. Simon Willison built a strtotime clone and Stoyan Stefanov did one as well. Integrating one of those libraries into your date handling routines is left as an exercise to the reader. ![]()
Let’s now put it all together into an interactive script:
About the author: Philip Tellis (