【问题标题】:Why is getting the `MMMM` format on the first day of the month returning the previous month using moment js?为什么使用moment js在一个月的第一天返回上个月的`MMMM`格式?
【发布时间】:2020-07-27 18:06:08
【问题描述】:

为什么在该月的第一天得到MMMM 格式返回上个月,但从该月的第二天开始返回正确的月份,使用这种格式2020-08-01T00:00:00Z?它与时区偏移量有关吗?下面的例子:

当月的第一天:

start = "2020-08-01T00:00:00Z";
month = moment(start).format("MMMM");
console.log(month) // <- July

当月的第二天:

start = "2020-08-02T00:00:00Z";
month = moment(start).format("MMMM");
console.log(month) // <- August

【问题讨论】:

标签: javascript momentjs


【解决方案1】:

是的,这是因为 Moment 对象在本地时区默认为 created。因此,如果您的本地时区是 UTC 减去任何时间,并且您使用午夜 UTC 时间字符串创建 moment,您将获得上个月的最后一天。

为了防止这种情况,您可以useutc()parseZone(),一个不包含时间的字符串,或者您可以使用moment-timezone 包指定时区:

start = "2020-08-01T00:00:00Z";
month = moment(start).format("MMMM");
monthUTC = moment(start).utc().format("MMMM"); // or moment.utc(start).format("MMMM");
monthPZ = moment.parseZone(start).format("MMMM");
monthNoTime = moment("2020-08-01").format("MMMM");

// Note: Requires separate moment-timezone package
monthLA = moment(start).tz('America/Los_Angeles').format("MMMM");
monthSYD = moment(start).tz('Australia/Sydney').format("MMMM");

console.log("Default: ", month);
console.log("UTC: ", monthUTC);
console.log("parseZone: ", monthPZ);
console.log("No time: ", monthNoTime);
console.log("LA: ", monthLA);
console.log("Sydney: ", monthSYD);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-10-year-range.min.js"></script>

【讨论】:

    猜你喜欢
    • 2013-08-30
    • 2017-01-09
    • 2012-04-20
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多