简体   繁体   English

使用 date-fns 将日期解析为 UTC 的正确方法

[英]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)我从日志提供者的文档中知道时间戳是用 UTC 编写的(尽管不使用 ISO 格式)

Now I want to parse them with date-fns :现在我想用 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:因为我的计算机的语言环境是 UTC+1,所以我看到的是:

> "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:这是我目前用来告诉 date-fns 解析为 UTC 的 hack:

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?有没有使用 date-fns 的正确方法? Looking for an equivalent to moment's moment.utc()寻找等效于moment.utc()

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, eg我不知道“正确”,但您可以使用zonedTimeToUtc将时间戳视为具有您喜欢的任何偏移量或时区,包括 UTC,例如

// Setup
var {parse} = require('date-fns');
var {zonedTimeToUtc} = require('date-fns-tz');

// Parse using location for offset
let loc = 'UTC';
let s   = '2020-12-03 08:30:00';
let fIn = 'yyyy-MM-dd HH:mm:ss';
let utcDate =  zonedTimeToUtc(s, loc);

// Show UTC ISO 8601 timestamp
console.log(utcDate.toISOString()); // "2020-12-03T08:30:00.000Z"

You can test it at npm.runkit.com/date-fns .您可以在npm.runkit.com/date-fns进行测试。

Example of using parse and zonedTimeToUtc使用 parse 和 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')
  })

I think you are looking for parseJSON , which supports a number of formats (but does not let you specify the source format).我认为您正在寻找parseJSON ,它支持多种格式(但不允许您指定源格式)。

Converts a complete ISO date string in UTC time, the typical format for transmitting a date in JSON, to a JavaScript Date instance.将 UTC 时间的完整 ISO 日期字符串(用于传输 JSON 中的日期的典型格式)转换为 JavaScript 日期实例。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM