Search code examples
javascripttypescriptdatetimezonedate-fns

Proper way to parse a date as UTC using date-fns


I have a log file with some timestamps

2020-12-03 08:30:00
2020-12-03 08:40:00
...

I know from the log provider's documentation that the timestamps are written in UTC (although not using ISO format)

Now I want to parse them with date-fns :

const toParse = "2020-12-03 08:40:00"
parse(toParse, 'yyyy-MM-dd HH:mm:ss', new Date()).toISOString()

And because the locale of my computer is in UTC+1 here is what I see:

> "2020-12-03T07:40:00Z"

expected:

> "2020-12-03T08:40:00Z".

Here is the hack I currently use to tell date-fns to parse as UTC :

const toParse = "2020-12-03 08:40:00"
parse(toParse + '+00', 'yyyy-MM-dd HH:mm:ss' + 'X', new Date()).toISOString()

And as expected,

> "2020-12-03T08:40:00Z".

Is there any proper way of doing this using date-fns? Looking for an equivalent to moment's moment.utc()


Solution

  • I don't know about "proper", but you can use zonedTimeToUtc to treat a timestamp as having any offset or timezone you like, including UTC, e.g.

    // Setup
    var {parse} = require('date-fns');
    var {zonedTimeToUtc} = require('date-fns-tz');
    
    // Parse an ISO 8601 timestamp recognised by date-fns
    let loc = 'UTC';
    let s1   = '2020-12-03 08:30:00';
    let utcDate =  zonedTimeToUtc(s1, loc);
    
    // Show UTC ISO 8601 timestamp
    console.log(utcDate.toISOString()); // "2020-12-03T08:30:00.000Z"
    
    // Parse non–standard format yyyyMMdd
    let s2 = '20210119';
    let fIn = 'yyyyMMdd';
    let d = zonedTimeToUtc(parse(s2, fIn, new Date()), loc);
    console.log(d.toISOString()); // "2021-01-19T00:00:00.000Z"```
    

    You can test it at npm.runkit.com/date-fns.