【问题标题】:Formatting Strings to Datetime using specific formats in Luxon使用 Luxon 中的特定格式将字符串格式化为日期时间
【发布时间】:2021-02-14 23:15:19
【问题描述】:

现在我使用moment-js 进行时间处理,但我想切换到Luxon。但我对以下实现有疑问。

有一个文本字段,您可以在其中以您的语言环境时间格式输入日期时间,例如HH:mm(24 小时格式)或hh:mm(12 小时格式)。使用的时间格式存储在变量timeFormat中。

我的解决方案moment-js

let timeFormat = 'HH:mm' // 'hh:mm a'
let textfield = document.querySelector('#input-time');
let timeString = textfield.value;
let dateTime = moment(timeString, timeFormat, true);

// Check if time is valid
if(dateTime.isValid() === false){
    return;
}

使用 12 小时格式:

  • 11:00 am09:43 pm有效
  • 11:0021:43 无效

使用 24 小时制:

  • 11:00 am09:43 pm无效
  • 11:0021:43有效

如何通过Luxon 获得类似的解决方案?我最大的问题是获得与moment(timeString, timeFormat, true) 类似的功能,因此使用特定格式将字符串格式化为日期时间,例如 12h/24 格式。

【问题讨论】:

    标签: javascript luxon


    【解决方案1】:

    你可以使用fromFormat方法

    从输入字符串和格式字符串创建日期时间。如果未指定区域设置,则默认为 en-US,无论系统的区域设置如何。

    例子:

    const DateTime = luxon.DateTime;
    const inputs = ['11:00 am', '09:43 pm', '11:00', '21:43'];
    const formats = ['HH:mm', 'hh:mm a'];
    
    const checkTime = (timeString, fmt) => 
      DateTime.fromFormat(timeString, fmt).isValid
    
    
    for (i=0; i<inputs.length; i++) {
      for (j=0; j<formats.length; j++) {
        console.log(`${inputs[i]} with format '${formats[j]}' is valid? ` + checkTime(inputs[i], formats[j]) );
      }
    }
    &lt;script src="https://cdn.jsdelivr.net/npm/luxon@1.25.0/build/global/luxon.js"&gt;&lt;/script&gt;

    查看手册的For Moment users 部分,以获得从 momentjs 迁移到 Luxon 的良好参考。

    【讨论】:

      猜你喜欢
      • 2017-04-09
      • 2022-10-13
      • 2017-08-21
      • 2012-09-07
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多