How to Set Common Format for toLocaleString?

I use JS function toLocaleString for date formatting. How can I set one common format for all clients like:

2015-10-29 20:00:00

That I do parsong at PHP by -

4

4 Answers

I think you would have to manually parse it into that format, which actually isn't too bad. What Date.toLocaleString() returns is a format of:

MM/DD/YYYY, HH:MM:SS

Here's my code snippet to help you out:

// Parse our locale string to [date, time]
var date = new Date().toLocaleString('en-US',{hour12:false}).split(" ");

// Now we can access our time at date[1], and monthdayyear @ date[0]
var time = date[1];
var mdy = date[0];

// We then parse  the mdy into parts
mdy = mdy.split('/');
var month = parseInt(mdy[0]);
var day = parseInt(mdy[1]);
var year = parseInt(mdy[2]);

// Putting it all together
var formattedDate = year + '-' + month + '-' + day + ' ' + time;
8

You can set the format as described (yyyy-mm-dd hh:mm:ss) by adding the locale parameter, like this:

toLocaleString("sv-SE")

References:

you can use moment.js library which has many features to work with date & time you can easily format a date with that.

here is an example moment().format('YYYY-MM-DD HH:mm:ss'); // will print in 2015-10-29 20:00:00 format

Moment.js

before doing what i provide please read this and this

var el = document.getElementById('dbg');
var log = function(val){el.innerHTML+='<div><pre>'+val+'</pre></div>'};
var pad = function(val){ return ('00' + val).slice(-2)};

Date.prototype.myFormattedString = function(){
  return this.getFullYear()     + '-' + 
        pad( (this.getMonth() + 1) )   + '-' + 
        pad( this.getDate() )          + ' ' + 
        pad( this.getHours() )         + ':' + 
        pad( this.getMinutes() )       + ':' +
        pad( this.getSeconds() )
    ;
}

var curDate = new Date();

log( curDate )
log( curDate.toLocaleString() )
log( curDate.myFormattedString() )
<div id='dbg'></div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest