MIRMIX
MIRMIX

Reputation: 1080

Time conversions in javascript

How to convert this type of a time

      Thu Jul 17 2014 09:52:30 GMT+0300 (Turkey Daylight Time)

to

      17 Jul 2014 09:52

and this

      17 Jul 2014

Upvotes: 0

Views: 67

Answers (2)

user2575725
user2575725

Reputation:

Try this code:

var formatDate = function (txt) {
    var dt = new Date(txt);
    var fmt = dt.getDate();
    var sp = " ";
    fmt += sp;
    fmt += ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][dt.getMonth()];
    fmt += sp;
    fmt += dt.getFullYear();
    return isNaN(dt) ? txt : fmt;
};

var formatDateTime = function (txt) {
    var dt = new Date(txt);
    var fmt = formatDate(txt);
    if (isNaN(dt)) {
        fmt = txt;
    } else {
        fmt += " ";
        fmt += dt.getHours();
        fmt += ":";
        fmt += dt.getMinutes();
    }
    return fmt;
};

console.log(formatDateTime("Thu Jul 17 2014 09:52:30 GMT+0300 (Turkey Daylight Time)"));

console.log(formatDate("Thu Jul 17 2014 09:52:30 GMT+0300 (Turkey Daylight Time)"));

Upvotes: 1

Mohit S
Mohit S

Reputation: 14044

Although JavaScript provides a bunch of methods for getting and setting parts of a date object, it lacks a simple way to format dates and times according to a user-specified mask.

Whateverdate.format("dd mmm yyyy hh:MM")
Whateverdate.format("dd mmm yyyy")

You can read more here

Upvotes: 0

Related Questions