【问题标题】:Get the format of time for any country获取任何国家/地区的时间格式
【发布时间】:2021-12-29 04:59:54
【问题描述】:

有没有办法在JS中获取基于时区的时间格式?我想要的是这样的:getSpecificTimeFormat("America/New_York") 返回 "h:mm a" 和 getSpecificTimeFormat("Europe/Paris") 返回 "HH:mm" 等等。

【问题讨论】:

  • 时间格式不依赖于时区,而是依赖于语言和文化。

标签: javascript time format timezone time-format


【解决方案1】:

此函数根据提供的语言环境字符串返回一个包含当前日期/时间格式数据的字符串。

function getDateFormatString(locale) {
    
  const options = {
    hour: "numeric",
    minute: "numeric",
    second: "numeric",
    day: "numeric",
    month: "numeric",
    year: "numeric",
  };

  const formatObj = new Intl.DateTimeFormat(locale, options).formatToParts(
    Date.now()
  );

  return formatObj
    .map((obj) => {
      switch (obj.type) {
        case "hour":
          return "HH";
        case "minute":
          return "MM";
        case "second":
          return "SS";
        case "day":
          return "DD";
        case "month":
          return "MM";
        case "year":
          return "YYYY";
        default:
          return obj.value;
      }
    })
    .join("");
}

console.log(getDateFormatString("en-US")); //Expected Output: "MM/DD/YYYY, HH:MM:SS PM"

console.log(getDateFormatString("ko-KR")); //Expected Output: "YYYY. MM. DD. 오후 HH:MM:SS"

编辑选项以更改从日期对象中提取的数据并编辑/添加案例以适应它。

查找 DateTimeFormat here 的文档。
我根据newbedev.com 上的一篇文章改编了这个函数。

【讨论】:

    【解决方案2】:

    在 mozilla.org 上有关于如何使用 .toLocaleTimeString() 函数执行此操作的明确说明。

    直接取自网站的示例:

    You can find the documentation here

    // Depending on timezone, your results will vary
    const event = new Date('August 19, 1975 23:15:30 GMT+00:00');
    
    console.log(event.toLocaleTimeString('en-US'));
    // expected output: 1:15:30 AM
    
    console.log(event.toLocaleTimeString('it-IT'));
    // expected output: 01:15:30
    
    console.log(event.toLocaleTimeString('ar-EG'));
    // expected output: ١٢:١٥:٣٠ص

    【讨论】:

    • 我会说这不能回答问题,因为 OP 必须解析响应
    【解决方案3】:

    获取时区

    - new Date().getTimezoneOffset() / 60
    

    根据时区获取时间

    const num=- new Date().getTimezoneOffset() / 60;
    
    const newDate=new Date(new Date().getTime()+num*60*60*1000).toISOString()
    

    【讨论】:

    • 问题是get the time format,不是格式化的时间
    • 我觉得这个在实际开发中经常用到
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-25
    • 1970-01-01
    相关资源
    最近更新 更多