【问题标题】:Unable to Create Date Object with Timezone Beside UTC in Lambda无法在 Lambda 中创建带有除 UTC 之外的时区的日期对象
【发布时间】:2019-10-17 16:49:27
【问题描述】:

我有一个用 Node.js 编写的 Lambda。它正在传递一个美洲/纽约时区日期时间字符串:

exports.handler = async (event) => {
    // Stub out the response object
    const response = {
        statusCode: 200,
        body: ""
    };

    const thingAsString = event.body.date; //This is a date/time expressed in local time
    const thingAsObject = new Date(thingAsString); //This is the date/time with a TZ of UTC.

    console.log("Before: %s", thingAsString );
    console.log("After: %s", thingAsObject.toISOString());

    return response;
};

问题是当我尝试将其转换为日期/时间对象时,它会将时区假定为 UTC。

有没有办法将其转换为不立即将时区设置为 UTC 的日期对象?

我尝试了momentmonent-timezone 的一些选项,但我遇到了同样的问题:

const original_date_string = "2019/10/15 14:21:14";
const original_date_object = new Date(original_date_string);
const original_date_object_est = moment.tz(original_date_object, 'America/New_York');
console.log("Original: %s", original_date_string);
console.log("UTC: %s", original_date_object_est.utc().toISOString());

【问题讨论】:

  • 2019/10/15 14:21:14 us 非标准日期字符串。期待其他奇怪的处理方式。
  • 我无法控制即将到来的日期。
  • 如果它以已知格式出现,那么您仍然可以通过在 Moment 中提供格式或使用原始 Date 对象进行自定义解析来正确解析它。
  • 同意@VLAZ。回答中的演示。

标签: node.js date datetime lambda momentjs


【解决方案1】:

像这样在创建时指定日期格式和时区...

const mtz = require('moment-timezone');
const moment = require('moment');

exports.handler = async (event) => {
    // Stub out the response object
    const response = {
        statusCode: 200,
        body: ""
    };
    // 2019/10/15 14:21:14
    const thingAsString = event.body.date;
    const thingAsObject = moment.tz(thingAsString, "YYYY/MM/DD HH:mm:ss", 'America/New_York');

    console.log(thingAsObject);
    console.log(thingAsObject.utc());

    return response;
};

【讨论】:

    猜你喜欢
    • 2019-06-27
    • 2019-06-05
    • 2015-12-10
    • 2020-09-07
    • 1970-01-01
    • 2022-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多