在当前时区中将日期时间作为字符串获取

Getting datetime as a string in current timezone

在 MySQL 数据库中:'2020-04-19 22:00:00'(UTC)。这也是我的端点 returns 因为我设置了连接选项 dataStrings:true.

在客户端上,在我获取 date 之后:

const timezone = moment.tz.guess();

const convertedDate = moment(date)
   .tz(timezone)
   .format();

convertedDate 则等于 "2020-04-19T22:00:00+02:00"(我在 UTC+2 时区)。

我想以“2020-04-20T00:00:00”的格式获取它。我该怎么做?

看起来 moment(date) 认为您传入的 date 值是当地时间,而不是 UTC。因此,您将时区转换为当地时间没有任何改变。你可以告诉 moment 它是 UTC,像这样:

const timezone = moment.tz.guess();

const convertedDate = moment.utc(date)
   .tz(timezone)
   .format();

您不需要时刻时区。借助 Moment 本身,您可以在解析时使用 utc 函数,并在格式化之前使用 local 函数转换为用户本地时区。

moment.utc('2020-04-19 22:00:00').local().format()

//=> "2020-04-20T00:00:00+02:00"

此外,Moment 团队建议仅对现有项目使用 Moment。对于新开发,我们建议使用 Luxon 代替:

luxon.DateTime.fromSQL('2020-04-19 22:00:00', {zone: 'utc'}).toLocal().toISO()

//=> "2020-04-20T00:00:00.000+02:00"