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

Viewed 16852

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

3 Answers

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.

I think you are looking for parseJSON, which supports a number of formats (but does not let you specify the source format).

Converts a complete ISO date string in UTC time, the typical format for transmitting a date in JSON, to a JavaScript Date instance.

import { parseJSON } from 'date-fns';
const utcDate = parseJSON('2020-12-03 08:40:00');

// Thu Dec 03 2020 19:40:00 GMT+1100 (Australian Eastern Daylight Time)

Example of using parse and zonedTimeToUtc

 it('should parse polish date', async () => {
    expect.assertions(1)
    const dateWithoutTime = '29 gru 2003'

    const parsed = parse(dateWithoutTime, 'd LLL yyyy', new Date(), {
      locale: pl,
    })

    const dateUTC = zonedTimeToUtc(parsed, 'UTC')

    expect(dateUTC.toISOString()).toStrictEqual('2003-12-29T00:00:00.000Z')
  })
Related