简体   繁体   中英

How to manipulate date time using vanilla javascript

I want to manipulate date which come from the api.

When I use: console.log(dataAPI.dateStation)

I see 2023-01-24T06:00:00.000Z

Is there way to change the date time in this format 2023-01-24 06:00:00

Just I want to remove T character between date and time and remove .000Z at the end.

The simplest way to do it is probably:

new Date(dataAPI.dateStation).toLocaleString()

If what you want is to display it somewhere, it'll automatically adapt the ISO date you have into a localized and readable date (based on timezone and language).

To know more about it and the options, here is the doc: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

Use the javascript date class with toLocaleString

new Date(dataAPI.dateStation).toLocaleString('en-US');

Without installing some third-party library, your best bet is probably to use the string you have (which is the format returned by toISOString() ),and modify it as desired. If it's already a string in the format you gave, you can just call replace on it:

dataAPI.dateStation.replace('T',' ').replace('.00Z','')

If it's a Date object, first call toISOString() to get a string:

dataAPI.dateStation.toISOString().replace('T',' ').replace('.00Z','')

If it's a string in a possibly-different format, call new Date() to get a Date object, then call toISOString() on that, and finally call replace on the result:

new Date(dataAPI.dateStation).toISOString().replace('T',' ').replace('.00Z','')

If you want to print the date in ISO 8601 format, you can use the 'sv' (Sweden) locale and Date.toLocaleString() .

You can also specify whichever IANA timezone you wish to use, I'm using UTC in this case.

 const d = '2023-01-24T06:00:00.000Z' let timestamp = new Date(d).toLocaleString('sv', { timeZone: 'UTC' }); console.log('Timestamp:', timestamp);

You can use regular expressions to remove the parts you don't want:

 let s = "2023-01-24T06:00:00.000Z" s = s.replace(/T/, ' ') s = s.replace(/\.\d{3}Z$/, '') console.log(s)

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