Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date format conversion in JavaScript

I wondering what is the best way to convert a timestamp of this format -

2012-02-18 14:28:32

to a date presentation of this format -

Saturday Feb 2012 14:28:32

Many thanks :)

like image 657
user1202278 Avatar asked Feb 18 '12 18:02

user1202278


People also ask

What date format is DD MMM YYYY JavaScript?

There is no native format in JavaScript for” dd-mmm-yyyy”. To get the date format “dd-mmm-yyyy”, we are going to use regular expression in JavaScript.

What is JavaScript default date format?

The string format should be: YYYY-MM-DDTHH:mm:ss. sssZ , where: YYYY-MM-DD – is the date: year-month-day. The character "T" is used as the delimiter.


2 Answers

You must first define an array of the English words (Sunday, Monday, Feb, Mar, etc.):

var daysOfWeek = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],
    monthsOfYear = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

To be able insert the extra 0 at the beginning of the minutes and seconds, define a padding function for the String prototype:

String.prototype.padLeft = function(padString,length){
    var toReturn = String(this);
    while(toReturn.length < length){
        toReturn = padString + toReturn;
    }
    return toReturn;
}

Format the date and time like this:

var time = new Date(), formattedDate, formattedTime, wholeThing;
formattedDate = daysOfWeek[time.getDay()] + ", " + monthsOfYear[time.getMonth()] + " " + time.getDate() + ", " + time.getFullYear();
formattedTime = time.getHours() + ":" + time.getMinutes().padLeft("0",2) + time.getSeconds().padLeft("0",2);

You can get the whole thing by concatenating formattedDate and formattedTime, as in:

wholeThing = formattedDate + " " + formattedTime;
like image 96
wecsam Avatar answered Oct 06 '22 09:10

wecsam


I'd suggest using an external js library to do that. To my understanding, Moment.js is the best date-time conversion library out there.

In this case, it does the job in one line. Just add the moment.js in you project and then do

var timestamp = '2012-02-18 14:28:32';
var formattedTime = moment(timestamp).format('dddd MMM YYYY HH:mm:ss'); // Saturday Feb 2012 14:28:32
like image 41
Ayush Goswami Avatar answered Oct 06 '22 07:10

Ayush Goswami