Date Formatting with YUI – Part I

By Philip TellisFebruary 11th, 2009

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.

8 Comments

  1. Looks interesting.
    Just a question, what about internationalization? Is there any support of it?

  2. What about locales? If I want the date in french for example…

  3. Hi Benjy,

    I’ll be talking about locales in a part IV of this series. Stay tuned.

    Philip

  4. Hi Valentin,

    Like I mentioned in response to Benjy, I’ll be covering internationalization in part IV.

  5. can i use YUI to parse a date string (strtotime?)

  6. You can use javascript’s native Date.parse() method or the Date constructor itself to parse dates of various formats. If you need something more complicated, then have a look at Simon Willison’s strtotime implementation.

  7. [...] Part I of this series, we introduced date formatting with the YUI Date utility and integrated it with the [...]

  8. [...] Part I, we saw how to format a date using YUI’s date formatter. In Part II, we’ll look at [...]