Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 -

like image 358
Xakerok Avatar asked Oct 10 '15 18:10

Xakerok


People also ask

What does the toLocaleString () method do in JS?

The toLocaleString() method returns a string with a language-sensitive representation of this date. In implementations with Intl. DateTimeFormat API support, this method simply calls Intl. DateTimeFormat .

Does toLocaleString round?

The toLocaleString() method will round the resulting value if necessary. The toLocaleString() method does not change the value of the original number.

How do you get toLocaleString time?

To get the current date and time in JavaScript, you can use the toLocaleString() method, which returns a string representing the given date according to language-specific conventions. To display only the time, you can use the toLocaleTimeString() method.


1 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;
like image 86
David Li Avatar answered Nov 06 '22 10:11

David Li