【问题标题】:Formatting date using moment.js using locale rather than explicit format使用区域设置而不是显式格式使用 moment.js 格式化日期
【发布时间】:2016-12-15 05:06:01
【问题描述】:

我们的日期选择器中的日期采用 DD/MM/YYYY h:mm A 格式。 目前,我们需要为 moment.js 明确提供格式,以便正确解释该日期,如下所示:

var dateFormats = ['DD/MM/YYYY h:mm A'];
var tmp1 = moment(date, dateFormats).format('YYYY-MM-DD HH:mm');

我们的偏好是避免硬编码日期格式,而是能够按如下方式应用语言环境:

var locale = (window.navigator.userLanguage || window.navigator.language).toLowerCase();
moment.locale(locale);
var tmp1 = moment(date).format('YYYY-MM-DD HH:mm');

当前,执行以下操作(在应用上述语言环境后):

moment('15/12/2016 2:27 PM').format('YYYY/MM/DD h:mm A');

给予:

"2017/03/12 2:27 PM"

何时需要给予:

"2016/12/15 2:27 PM"

我们怎样才能做到这一点?

【问题讨论】:

    标签: datetime momentjs datetime-format


    【解决方案1】:

    如果您的输入字符串具有特定于语言环境的格式,您可以使用 moment 的 localeData 来解析它。使用longDateFormat(dateFormat); 可以获得本地化格式。

    这是一个使用 en-au 语言环境的工作示例:

    moment.locale('en-au');
    var input = '15/12/2016 2:27 PM';
    var s = moment(input).format('YYYY/MM/DD h:mm A'); // Gives Deprecation warning
    console.log(s); // Invalid date
    
    // Get locale data
    var localeData = moment.localeData();
    var format = localeData.longDateFormat('L') + ' ' + localeData.longDateFormat('LT');
    s = moment(input, format).format('YYYY/MM/DD h:mm A');
    console.log(s); // 2016/12/15 2:27 PM
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.0/moment-with-locales.min.js"></script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多