简体   繁体   中英

How to convert a string date to date format?

I have:

Thu Apr 23 2020 00:00:00 GMT+0200 (Ora legale dell’Europa centrale)

I tried:

dateStart = new Date(dateStart);

But that's not the right

I'm looking at 23/4/20

Something like

const dateStart = new Date('Thu Apr 23 2020 00:00:00 GMT+0200');
const formatted = `${dateStart.getDate()}/${dateStart.getMonth() + 1}/${dateStart.getFullYear().toString().substr(-2)}`

if, when you think about manipulating Date object you think about MomentJs... don't rush! you might not even need it's 66Kb for a very simple thing!

in your case, it's quite simple:

as you have already a date() object, reading the docs , you have access to all parts of the date, though getMonth() get's a bit weird ♂️

so:

 var dateStart = new Date() var dateAsString = `${dateStart.getDate()}/${dateStart.getMonth()+1}/${dateStart.getFullYear().toString().substr(-2)}` console.log(dateAsString)

In Nodejs. library . Snippet

const DATE_FORMATER = require( 'dateformat' );
let datetime = DATE_FORMATER( new Date(dateStart), "dd/mm/yy" );
console.log(datetime);

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