Formatting a Date String

The best way to take a string that is formed as ...

YYYY-MM-DD

and make it look like ...

MM/DD/YYYY

The reason it is not a javascript date object is because I work with a huge amount of data and these dates are retrieved from the database.

I do not see the need to convert it to a date object.

+3
source share
4 answers

What about:

s.substr(5,2) + '/' + s.substr(8) + '/' + s.substr(0,4)
+4
source

With brute force you can do something like:

var old = '2010-02-03'.split('-');
var desired = old[1] + '/' + old[2] + '/' + old[0];

Saves the problem of working with the Date object.

+1
source

JavaScript ( JS, ):

var date = "2010-05-09";
var formatted = date.replace(/([0-9]{4})-([0-9]{2})-([0-9]{2})/, "$2/$3/$1")

, , , , .

+1

If you replace the dash with a slash, it will be parsed, then you can use the date functions to get different components (or convert to a string using one of the different toString () functions).

var date = new Date( Date.parse( old.replace(/-/g,'/') ) );
alert( date.getMonth() + '/' + date.getDate() + '/' + date.getFullYear() );

This has the advantage that you can use the date as a date for calculations, rather than just formatting the strings. If string formatting is all you need. And , date strings are always valid, then using the @Guffa substr method is probably the best way to handle this.

+1
source

Source: https://habr.com/ru/post/1731258/


All Articles