javascript - 使用 jquery globalize 格式化 moment.js + 时区

标签 javascript jquery date momentjs jquery-globalize

我使用 moment.js + timezone 来处理日期和时间对象,并使用全局化来向用户显示数字、货币等。

现在我想用全局化打印一个 moment.js 日期,所以我的第一个方法是只使用 moment.js 的 getDate() 函数,不幸的是它会丢弃时区信息(Ex 1)。当我初始化一个新的 Date() 并将日期值转换为正确的时区时,我得到了正确的结果(Ex 2),但是当我使用完整版本时,它显示时区 UTC(这显然不正确)。有没有办法让这些组件协同工作?

var m = moment.tz(1459779436, 'Europe/Berlin');
// Ex 1: Date is printed in UTC, so with an offset of 2 hours
globalize.formatDate(m.getDate(), {datetime: 'full'});
globalize.formatDate(new Date(m.toISOString()), {datetime: 'full'});
// Ex 2: Correct times are printed, but with wrong timezone
globalize.formatDate(new Date(m.year(), m.month(), m.date(), m.hour(), m.minute(), m.seconds(), m.milliseconds()), {datetime: 'full'});

最佳答案

我现在使用了一种非常hacky的方法,只是用一个返回时刻时区生成的值的函数替换了新日期的getTimezoneOffset。

function momentToDate(input) { // Do NOT use the result to anything else than passing it into globalize
    var res = new Date(input.year(), input.month(), input.date(), input.hour(), input.minute(), input.seconds(), input.milliseconds());
    var offset = input.utcOffset();
    res.getTimezoneOffset = function() {
        return offset;
    }
    return res;
}

因此全局化将打印正确的日期和正确的时区偏移量。

关于javascript - 使用 jquery globalize 格式化 moment.js + 时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36405266/

相关文章:

javascript - angularjs从外部 Angular 重定向

php - MongoDB - 组合多个命令来发送和返回一个请求

javascript - Filter.js 如何在初始化时过滤 jquery UI slider

java - 在当前日期上添加天数

javascript - 使用 JQuery 获取类的中间值

javascript - ReactJS - child 如何访问它是 parent 的 Prop ?

javascript - 检查多个输入空值不起作用

javascript - 实时表单验证未出现在某些输入中

sql - 在 PostgreSQL 中按月选择

java - 如何在 Java 中验证日期?