简体   繁体   中英

How to convert date in javascript?

I try to use new Date() in javascript, and it display like this

Sat Dec 17 2016 00:00:00 GMT+0800 (your country standard time)

but I want to convert to display like this

2020-02-05T06:23:34

I try to search it in google but I don't know the term that Im gonna use to search the date.

new Date().toJSON().slice(0,19)

You can use Date.toISOString

The timezone is always zero UTC offset, as denoted by the suffix "Z"

 console.log(new Date(`Sat Dec 17 2016 00:00:00 GMT+0800 `).toISOString()) 

You can use the Following Methods:

let date = new Date().toISOString().slice(0,19)

or

let date = new Date().toJSON().slice(0,19)

You can find similar methods from here: https://www.w3schools.com/jsref/jsref_toisostring.asp

You can use moment.js library for that

 var date=new Date(); let c=moment(date).format(); console.log(c) let s=c.split("+") console.log(s[0]) 
 <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script> 

With vanilla JS you could use toISOString . Go ahead and try

(new Date()).toISOString(); .

Output would be in this format: "2019-02-01T05:43:11.618Z" .

If you don't need the time zone you can format it, or use character handling.

Otherwise, use a library like moment.js or date-fns to handle date formatting.

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