Home > OS >  How to manipulate date time using vanilla javascript
How to manipulate date time using vanilla javascript

Time:01-25

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.

CodePudding user response:

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

CodePudding user response:

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);

CodePudding user response:

Use the javascript date class with toLocaleString

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

CodePudding user response:

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','')

CodePudding user response:

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)

  • Related