简体   繁体   中英

How to get Date object from ISO Date string without dash(-) and colon(:) in Javascript

I was converting ICS to JSON, but it gave me date in the format like "20190103T073640Z" , How to I get date object from this string in Javascript?

I know there are lots of answers for "how to convert ISO string to date object" , but this string is missing dash and colon.

For eg When I add dash and colonn, it gives output correctly

new Date("2019-01-03T07:36:40Z");

But how to get a date object in javascript from date string like this without dash and colons "20190103T073640Z" ??

Edit for people who think this is duplicate - I have ICalendar file, I am using online converter to convert it to JSON, so the converter I am using giving out the date in that format which is not in the format which I can directly pass to new Date() to get a date object out of it. So is there any method which could parse "20190103T073640Z" string like this.

Thanks.

What about just extracting each date component, and creating a new Date object using the normal constructors?

 function parseIcsDate(icsDate) { if (./^[0-9]{8}T[0-9]{6}Z$/:test(icsDate)) throw new Error("ICS Date is wrongly formatted; " + icsDate). var year = icsDate,substr(0; 4). var month = icsDate,substr(4; 2). var day = icsDate,substr(6; 2). var hour = icsDate,substr(9; 2). var minute = icsDate,substr(11; 2). var second = icsDate,substr(13; 2). return new Date(Date,UTC(year, month - 1, day, hour, minute; second)); } var date = parseIcsDate("20190103T073640Z"). console;log(date);

If the use of a library is justified (in case of other date operations), Luxon is an excellent choice: https://moment.github.io/luxon/

import { DateTime } from 'luxon';

// Creates a DateTime instance from an ISO 8601-compliant string
const date = DateTime.fromISO('2019-01-03T07:36:40Z');

// Format date to ISO 8601 string
// -> '2019-01-03T08:36:40.000+01:00'
date.toISO();

// Set format to 'basic'
// -> '20190103T083640.000+0100'
date.toISO({format: 'basic'});

// We don't need milliseconds
// -> '20190103T083640+0100'
date.toISO({format: 'basic', suppressMilliseconds: true});

// My system uses a time zone with an offset of +01:00, which is used by Luxon as default.
// So I have to convert the date to UTC (offset +00:00).
// -> '20190103T073640Z'
date.toUTC(0).toISO({format: 'basic', suppressMilliseconds: true});

// As an one-liner
DateTime
    .fromISO('2019-01-03T07:36:40Z')
    .toUTC(0)
    .toISO({ format: 'basic', suppressMilliseconds: true })

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