Converting ISO-8601 string to local date in typescript/javascript
Asked Answered
B

2

6

I am developing in Angular 6. I keep form values as json in a database when new record is saved.If end user wants to show exists record , I fill form components from json data.But I got into trouble for casting date values . I wasn't be able to cast correctly my local date. I have tried with moment,but didn't work:

console.log("string Value",stringValue);
let date = moment(stringValue,"yyyy-mm-ddThh:mm:ss.fffZ");                             
console.log("date",date.format('DD/MM/YYY HH:mm:ss'));

string Value output: 2019-01-17T21:00:00.000Z

console output actual : date 18/01/2019 01:00:00

but console output expected : date 18/01/2019 00:00:00

I tried "YYYY-MM-DDThh:mm:ss.fffZ" but didn't work too.

EXTRA INFORMATION

saving data:

process.data = JSON.stringify(this.form.getRawValue());
save(process);

html(primeng):

<p-calendar formControlName="startDate" dateFormat="dd.mm.yy"></p-calendar>
Burble answered 18/1, 2019 at 9:4 Comment(3)
Which time zone are you in?Executioner
@Executioner GMT+03:00 IstanbulBurble
Did you check the time zone settings of your computer? Maybe it is caused by a wrong DST configuration. What browser / OS version are you using?Executioner
P
6

You can parse your '2019-01-17T21:00:00.000Z' input using moment.utc() since it represents time in UTC

By default, moment parses and displays in local time.

If you want to parse or display a moment in UTC, you can use moment.utc() instead of moment().

and then convert it to local timezone using local().

Here a live sample:

const stringValue = '2019-01-17T21:00:00.000Z';
let date = moment.utc(stringValue).local();
console.log("date", date.format('DD/MM/YYYY HH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
Prom answered 18/1, 2019 at 9:21 Comment(4)
Weird. If the input string ends with "Z", moment should understand that it is UTC without the explicit .utc().Kroo
@Prom I tried it but I set to form control wrongly, thanksBurble
@Kroo Z stands for +00:00, I think that it is fine that moment implicitly understand that input is UTC. moment('2019-01-17T21:00:00.000Z') would give the same output of the code in my answer, but I think that using moment.utc() and local() is clearer. Probably the biggest issue in the OP code was yyyy-mm-ddThh:mm:ss.fffZ tokens.Prom
If anyone is still looking at this answer, moment.js is deprecated. You shouldn't be using this library anymore.Hermie
H
0

The moment-timezone library was built to "parse and display dates in any timezone".

To construct a date-time object in a specific timezone, use:

let now = moment.tz('Europe/Istanbul');

To view the UTC value, use

now.toISOString()

To view the local timezone value, use:

now.format('YYYY-MM-DD HH:mm:ss.SSS');
Hardunn answered 18/1, 2019 at 16:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.