Reputation: 138
I'm attempting to use the dayjs lib to parse incoming ISO strings. I need the output to be in UTC time, not converted to my machine's local timezone.
This is my rough draft code:
const dayjs = require("dayjs");
const utc = require("dayjs/plugin/utc");
dayjs.extend(utc);
const formats = ["YYYY-MM-DDTHH:mm:ss[Z]", "YYYY-MM-DD"];
const validateDate = (date) => {
if (!date.isValid()) {
throw new Error(`Invalid date format given (${date})`);
}
};
exports.parseISOString = (dateString) => {
const parsedDate = dayjs.utc(dateString, formats, false);
console.dir(parsedDate.utc().format("YYYY-MM-DD HH:mm:ss"))
validateDate(parsedDate);
return parsedDate.toDate();
};
Here is the output from some tests I've written beforehand. The green is the console.dir
from the function, and the red text contains the ISO string passed into the function.
As you can see, dayjs appears to be converting the dates to my machine's local time (NZT), despite the fact that I'm using the utc plugin. Is there something I'm doing wrong for this to be happening?
Upvotes: 0
Views: 989
Reputation: 138
I tried removing the additional params from the days.utc()
call, and only passing the date:
const parsedDate = dayjs.utc(dateString);
This ended up returning the correct date and time (in utc time). The only issue being that this will now accept any date string, so I have to do some further validation on this incoming date string with regex, but such is life I guess.
const dayjs = require("dayjs");
const utc = require("dayjs/plugin/utc");
dayjs.extend(utc);
// https://stackoverflow.com/questions/12756159/regex-and-iso8601-formatted-datetime
// eslint-disable-next-line
const re = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;
/**
* Validates a date string against an ISO 8601 format using a regular expression.
* If the date string does not match the ISO 8601 format, it throws an error.
*
* @param {string} date - The date string to be validated.
* @throws {Error} Throws an error if the date format is invalid.
*/
const validateDate = (date) => {
if (!re.test(date)) {
console.error(`${date} is in an invalid format.`);
throw new Error(`Invalid date format given (${date})`);
}
};
/**
* Parses an ISO string date and returns a JavaScript Date object.
*
* @param {string} dateString - The ISO string date to be parsed.
* @returns {Date} A JavaScript Date object.
* @throws {Error} Error if date string is in an invalid non-ISO format
*/
exports.parseISOString = (dateString) => {
validateDate(dateString);
const parsedDate = dayjs.utc(dateString);
return parsedDate.toDate();
};
Upvotes: 0