Date Formatting with YUI – Part I

By YUI TeamFebruary 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=""></script> 
<script type="text/javascript" src=""></script> 
<script type="text/javascript" src=""></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"}));

Let’s try something more interactive. We’ll throw in some markup to read in a format and display the output:

<label>Enter a format: <input type="text" name="date-format" id="date-format" value=""></label><br>
<input type="submit" value="Show Me!" id="btnShow">
<div id="messages">


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.example.DateFormatter.formatDate = function(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);


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.


  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.


  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 [...]