Date Formatting with YUI - Part I

By YUI TeamFebruary 12, 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.