简体   繁体   中英

Js format a date string

I get a JSON array from a rest call and one of its objects has got an attribute lastModified which is formatted such as:

'lastModified: "2018-03-19 13:02:53.0 UTC"' 

I want to display it as a label on a radio button but not as "2018-03-19 13:02:53.0 UTC", what I want is to format it as "19 Mar 13:02".

How to format date and time in the way I want when showed?

One of the easiest way is to use moment.js library.

moment("2018-03-19 13:02:53.0 UTC").format('DD MMM HH:mm');

Demo: http://jsfiddle.net/ycu3p6tx/

Try this to create your Date object:

 var data = 'lastModified: "2018-03-19 13:02:53.0 UTC"'; var lastModified = data.split('"')[1].split(' '); console.log(lastModified); var datetime = new Date(lastModified[0] + 'T' + lastModified[1] + 'Z'); console.log(datetime); 

Then use some library to format it as you need (for example moment.js)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM