Monday, June 11, 2012

Formatting a date in JavaScript


I noticed that JavaScript's new Date() function is very smart in accepting dates in several formats.




Xmas95 = new Date("25 Dec, 1995 23:15:00")
Xmas95 = new Date("2009 06 12,12:52:39")
Xmas95 = new Date("20 09 2006,12:52:39")



I could not find documentation anywhere showing all the valid string formats while calling new Date() function.



This is for converting a string to date. If we look at the opposite side that is converting date object to string, until now I was under the impression that JavaScript doesn't have a built-in API to format a date object into a string.



Today, I played with the toString() method on the date object and surprisingly it serves the purpose of formatting date to strings.




var d1=new Date();
d1.toString('yyyy-MM-dd'); //returns "2009-06-29"
d1.toString('dddd, MMMM ,yyyy') //returns "Monday, June 29,2009"



Also here I couldn't find any documentation on all the ways we can format the date object into a string.



Where is the documentation which lists the format specifiers supported by the Date() object?


Source: Tips4all

15 comments:

  1. I love 10 ways to format time and date using JavaScript and Working with Dates.

    Basically, you have three methods and you have to combine the strings for yourself:

    getDate(): Returns the date
    getMonth(): Returns the month
    getFullYear(): Returns the year


    Example:

    <script type="text/javascript">
    var d = new Date();
    var curr_date = d.getDate();
    var curr_month = d.getMonth() + 1; //Months are zero based
    var curr_year = d.getFullYear();
    document.write(curr_date + "-" + curr_month + "-" + curr_year);
    </script>

    ReplyDelete
  2. If you are already using jQuery UI in your project, you can use the built-in datepicker method for formatting your date object:

    $.datepicker.formatDate('yy-mm-dd', new Date(2007, 1 - 1, 26));


    However, the datepicker only formats dates, and cannot format times.

    Have a look at jQuery UI datepicker formatDate, the examples.

    ReplyDelete
  3. Make sure you checkout Datejs when dealing with dates in JavaScript. It's quite impressive and well documented as you can see in case of the toString function.

    ReplyDelete
  4. Moment.js

    It is a lightweight (3.7 KB) JavaScript date library for parsing, manipulating, and formatting dates.

    var a = moment([2010, 1, 14, 15, 25, 50, 125]);
    a.format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Sunday, February 14th 2010, 3:25:50 pm"
    a.format("ddd, hA"); // "Sun, 3PM"

    ReplyDelete
  5. The functionality you cite is not standard Javascript, not likely to be portable across browsers and therefore not good practice. The ECMAScript 3 spec leaves the parse and output formats function up to the Javascript implementation. ECMAScript 5 adds a subset of ISO8601 support. I believe the toString() function you mention is an innovation in one browser (Mozilla?)

    Several libraries provide routines to parameterize this, some with extensive localization support. You can also check out the methods in dojo.date.locale.

    ReplyDelete
  6. DateJS is certainly full-featured, but I'd recommend this MUCH simpler lib (JavaScript Date Format) which I prefer simply because it's only 120 lines or so.

    ReplyDelete
  7. Just another option, which I wrote:

    DP_DateExtensions Library

    Not sure if it'll help, but I've found it useful in several projects - looks like it'll do what you need.

    Supports date/time formatting, date math (add/subtract date parts), date compare, date parsing, etc. It's liberally open sourced.

    No reason to consider it if you're already using a framework (they're all capable), but if you just need to quickly add date manipulation to a project give it a chance.

    ReplyDelete
  8. I came across a brand new JavaScript library called jPaq which provides a function that closely emulates PHP's date function. Documentation for this function can be found here: http://jpaq.org/documentation/Date.prototype.format%28%29/1.0/.

    ReplyDelete
  9. function dateToYMD(date)
    {
    var d = date.getDate();
    var m = date.getMonth()+1;
    var y = date.getFullYear();
    return '' + y +'-'+ (m<=9?'0'+m:m) +'-'+ (d<=9?'0'+d:d);
    }

    ReplyDelete
  10. I use Steven Levithan's date formatter. It's nice, easy and fully customizable.
    He's the author of Regular Expressions Cookbook (O'Reilly).

    ReplyDelete
  11. JsSimpleDateFormat is a library that can format the date object and parse the formatted string back to Date object. It uses the Java format (SimpleDateFormat class). The name of months and days can be localized.

    Example:

    var sdf = new JsSimpleDateFormat("EEEE, MMMM dd, yyyy");
    var formattedString = sdf.format(new Date());
    var dateObject = sdf.parse("Monday, June 29, 2009");

    ReplyDelete
  12. The library "f" is for Format is the most useful thing I've found when it comes to Date formatting in JavaScript. Not only does it make formatting a piece of cake, but it has some other cool features as well!

    ReplyDelete
  13. Formatting and especially parsing dates in JavaScript can be a bit of a headache. Not all browsers handle dates in the same way. So while it's useful to know the base methods, its more practical to use a helper library.

    The XDate javascript library by Adam Shaw has been around since mid-2011 and is still under active development. It has fantastic documentation, a great API, formatting, tries to remain backwards-compatible and even supports localized strings.

    ReplyDelete
  14. date.js seems to be the standard JS Date Swiss army knife.

    http://code.google.com/p/datejs/

    ReplyDelete
  15. It may appear that jQuery or some other library have extended your Date object with advanced version of toString method.
    In my case it was jQuery.

    ReplyDelete