Ben Pearce
Ben Pearce

Reputation: 7094

datetime formatting in javascript

When I generate a date with the following code

var date = new Date();

I get a date-time of the following form

Sat May 11 2013 21:54:23 GMT-0700 (PDT)

Can anyone tell me how to generate a date of the form below without using regex/string functions.

Sat May 11 2013 21:54:23

Upvotes: 0

Views: 87

Answers (2)

jfriend00
jfriend00

Reputation: 707318

Javascript does not come with a date formatting library beyond the one specific format you see. You can either build your own by piecing together the exact pieces you want and adding the strings together or you can get a third party date formatting library.

If you want a 3rd party library, the Datejs library is pretty thorough. In that library, it would be:

Date.today().toString("ddd MMM d yyyy H:mm:ss");

You could, of course obtain all the component values from the built-in date object and then build your own string too.

Without adding a library, you'd have to write your own way to make that specific format:

function formatDate(date) {
    function makeTwoDigits(val) {
        var prefix = val <= 9 ? "0" : "";
        return prefix + val;
    }
    var dayOfWeek = date.getDay();                  // 0-6, 0=Sunday
    var month = date.getMonth();                    // 0-11
    var day = date.getDate();                       // 1-31
    var year = date.getFullYear();                  // 2013
    var hours = makeTwoDigits(date.getHours());     // 0-23
    var mins = makeTwoDigits(date.getMinutes());    // 0-59
    var secs = makeTwoDigits(date.getSeconds());    // 0-59

    var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

    return days[dayOfWeek] + " " + months[month] + " " + day + " " + year + " " +
           hours + ":" + mins + ":" + secs;
}

Working demo: http://jsfiddle.net/jfriend00/zu7Uz/

Upvotes: 1

adamj
adamj

Reputation: 4782

Try giving this a shot: http://blog.stevenlevithan.com/archives/date-time-format

It has a collection of Date format options that I believe would give you what you desire.


Ignoring the above Javascript library and doing it native:

var date = new Date();
date = date.toDateString() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();

Does this work ok for you?

Upvotes: 1

Related Questions