date-fns | How do I format to UTC

泄露秘密 提交于 2020-01-05 03:44:25

问题


Problem

It looks like when I use the format() function, it automatically convert the original UTC time into my timezone (UTC+8). I have been digging through their docs for hours and couldn't seem to find a way to default it to UTC time.

import { parseISO, format } from "date-fns";

const time = "2019-10-25T08:10:00Z";

const parsedTime = parseISO(time);
console.log(parsedTime); // 2019-10-25T08:10:00.000Z

const formattedTime = format(parsedTime, "yyyy-MM-dd kk:mm:ss");
console.log(formattedTime); // 2019-10-25 16:10:00 <-- 8 HOURS OFF!!

I have tried to use the package data-fns-tz and use something like

format(parsedTime, "yyyy-MM-dd kk:mm:ss", {timeZone: "UTC"});

still no luck.

Please help!

Expected Output

2019-10-25 08:10:00

Actual Output

2019-10-25 16:10:00


回答1:


I would suggest using the built-in Date util:

const date = new Date("2019-10-25T08:10:00Z");
const isoDate = date.toISOString();

console.log(`${isoDate.substr(0, 10)} ${isoDate.substr(11, 8)}`);

Outputs:

2019-10-25 08:10:00

Not a general solution for any format, but no external libraries required.




回答2:


I had the same problem. What I do is remove the timezone from the ISO string and then use that time with date-fns:

let time = "2019-10-25T08:10:00Z".slice(0, -1)

The above is a time with to time zone, and because there is no timezone date-fns assumes the local timezone, so when you do:

format(parseISO(time), 'h:mm a')

you get: 8:10 AM, or whatever format you prefer. You just have to be careful with the string that you are slicing. If its always the same format then it should work.



来源:https://stackoverflow.com/questions/58561169/date-fns-how-do-i-format-to-utc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!