如何将 ISO 8601 格式的日期值转换为 JavaScript 中的日期对象?

发布于 2024-07-13 12:16:15 字数 230 浏览 12 评论 0原文

我一直在尝试将日期值转换为更易读的格式。 为此,我尝试使用 JavaScript Date.parse() 方法来解析日期。 然而,这不适用于我的输入(例如:“2007-09-21T14:15:34.058-07:00”)。 最终目标是输出一个日期字符串,如 “January 30th, 2008 @ 2:15PM”

有任何想法吗?

I've been trying to convert a date value into a more readable format. To do that, I'm trying to parse the date using the JavaScript Date.parse() method. That however does not work on the input (eg: "2007-09-21T14:15:34.058-07:00") that I have. The end goal is to output a date string like "January 30th, 2008 @ 2:15PM".

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烟雨凡馨 2024-07-20 12:16:15

您可能应该使用datejs f3lix 推荐,但是我很无聊,拼凑了一个小对象,它完全符合您的要求:

2012 年 9 月 25 日:清理代码,允许非扩展格式,例如 20120925T164740+0200< /em>

2011 年 12 月 1 日:修复了月份字符串中的错误。 August wasmissing

var ISODate = {
  convert :
    function (input){
      if (!(typeof input === "string")) throw "ISODate, convert: input must be a string";
      var d = input.match(/^(\d{4})-?(\d{2})-?(\d{2})[T ](\d{2}):?(\d{2}):?(\d{2})(\.\d+)?(Z|(?:([+-])(\d{2}):?(\d{2})))$/i);
      if (!d) throw "ISODate, convert: Illegal format";
      return new Date(
        Date.UTC(
          d[1], d[2]-1, d[3],
          d[4], d[5], d[6], d[7] || 0 % 1 * 1000 | 0
        ) + (
          d[8].toUpperCase() === "Z" ? 0 :
            (d[10]*3600 + d[11]*60) * (d[9] === "-" ? 1000 : -1000)
        )
      );
    },
  format :
    function(date, utc){
      if (typeof date === "string") date = this.convert(date);
      if (!(date instanceof Date)) throw "ISODate, format: t is not a date object";

      var t={'FullYear':0, 'Month':0, 'Date':0, 'Hours':0, 'Minutes':0, 'Seconds':0};
      for (var key in t) {
        if (t.hasOwnProperty(key)) t[key] = date["get" +(utc ? "UTC" :"") + key]()
      }

      return this.month[t.Month]
        + " "
        + this.ordinal(t.Date)
        + ", "
        + t.FullYear
        + " @ "
        + this.clock12(t.Hours,t.Minutes);
      },
  month:
    [
      "January", "February", "March", "April", "May", "June",
      "July", "August", "September", "October", "November", "December"
    ],
  ordinal:
    function(n) {
      return n+(
        [
          "th", "st", "nd", "rd"
        ][
          (( n % 100 / 10) | 0) === 1 ? 0 : n % 10 < 4 ? n % 10 : 0
        ]
      );
  },
  clock12:
    function(h24, m, s){
      h24%=24;
      var h12 = (h24 % 12) || 12;
      return h12 + ":" +
        (m < 10 ? "0" + m : m) +
        (isFinite(s) ? ":" + (s < 10 ? "0" + s : s ) : "") +
        (h24 < 12 ? "AM" : "PM");
      }
};

示例:

//Shows the date in the users timezone:
alert(ISODate.format("2007-09-21T14:15:34.058-07:00"));

//Show the date in UTC (Timezone Z, 00:00)
alert(ISODate.format("2007-09-21T14:15:34.058-07:00",true));

说明:

convert 将字符串作为输入,如果成功则返回日期对象,否则抛出异常。 该字符串必须采用以下格式之一:

  • YYYY-MM-DDThh:mm:ss.sZ
  • YYYY-MM-DDThh:mm:ss.sXaa:bb

其中:

  • YYYY 是 4 位整数形式的年份
  • MM 是月份作为 2 位整数
  • DD 是月份的日期,作为 2 位整数
  • T 是字符 T 或空格 (\x20)
  • hh 是 24 小时格式的小时,作为 2 位整数
  • mm 是作为 2 位整数的分钟
  • ss.s 是第二个,可以是 2 位整数,也可以是 2 位浮点数,后跟句点,后跟一位或多位数字。
  • Z 是字符 Z(表示时区 Z,UTC+00:00)
  • X 是相对于 UTC 的时间偏移量的加号 (+) 或减号 (-)
  • aa 是相对于 UTC 的时间偏移量的小时数
  • bb 是以 2 位整数表示的 ITC 时间偏移分钟

format 接受上述格式的字符串或日期对象,并返回格式为:

  • MD, Y @ h:mm 的

字符串
- M 是月份的英文全称
- D 是带有数字顺序后缀的月份日期(1-2 位数字)
- Y 是年份(1 位或多位数字)
- h 是 12 小时格式的小时(1-2 位数字)
- m 是分钟(2 位数字)

month 是一个包含月份名称的数组

ordinal 是一个函数,它以数字作为输入并返回带有英文序数的数字后缀。

clock12 是一个函数,它将 24 小时格式的小时、分钟和秒转换为美国 12 小时格式的字符串。 是可选的。

You should probably use the datejs that f3lix recommended, however I was bored and threw together a little object that does exactly what you asked for:

September 25, 2012: Cleaned code, allow non-extended format, eg 20120925T164740+0200

December 1, 2011: fixed a bug in the month string. August was missing

var ISODate = {
  convert :
    function (input){
      if (!(typeof input === "string")) throw "ISODate, convert: input must be a string";
      var d = input.match(/^(\d{4})-?(\d{2})-?(\d{2})[T ](\d{2}):?(\d{2}):?(\d{2})(\.\d+)?(Z|(?:([+-])(\d{2}):?(\d{2})))$/i);
      if (!d) throw "ISODate, convert: Illegal format";
      return new Date(
        Date.UTC(
          d[1], d[2]-1, d[3],
          d[4], d[5], d[6], d[7] || 0 % 1 * 1000 | 0
        ) + (
          d[8].toUpperCase() === "Z" ? 0 :
            (d[10]*3600 + d[11]*60) * (d[9] === "-" ? 1000 : -1000)
        )
      );
    },
  format :
    function(date, utc){
      if (typeof date === "string") date = this.convert(date);
      if (!(date instanceof Date)) throw "ISODate, format: t is not a date object";

      var t={'FullYear':0, 'Month':0, 'Date':0, 'Hours':0, 'Minutes':0, 'Seconds':0};
      for (var key in t) {
        if (t.hasOwnProperty(key)) t[key] = date["get" +(utc ? "UTC" :"") + key]()
      }

      return this.month[t.Month]
        + " "
        + this.ordinal(t.Date)
        + ", "
        + t.FullYear
        + " @ "
        + this.clock12(t.Hours,t.Minutes);
      },
  month:
    [
      "January", "February", "March", "April", "May", "June",
      "July", "August", "September", "October", "November", "December"
    ],
  ordinal:
    function(n) {
      return n+(
        [
          "th", "st", "nd", "rd"
        ][
          (( n % 100 / 10) | 0) === 1 ? 0 : n % 10 < 4 ? n % 10 : 0
        ]
      );
  },
  clock12:
    function(h24, m, s){
      h24%=24;
      var h12 = (h24 % 12) || 12;
      return h12 + ":" +
        (m < 10 ? "0" + m : m) +
        (isFinite(s) ? ":" + (s < 10 ? "0" + s : s ) : "") +
        (h24 < 12 ? "AM" : "PM");
      }
};

Example:

//Shows the date in the users timezone:
alert(ISODate.format("2007-09-21T14:15:34.058-07:00"));

//Show the date in UTC (Timezone Z, 00:00)
alert(ISODate.format("2007-09-21T14:15:34.058-07:00",true));

Explanation:

convert takes a string as an input and returns a date object if successful or throws an exception if not. The string must be in one of the following formats:

  • YYYY-MM-DDThh:mm:ss.sZ
  • YYYY-MM-DDThh:mm:ss.sXaa:bb

Where:

  • YYYY is the year as an 4 digit integer
  • MM is the month as an 2 digit integer
  • DD is the date of month as an 2 digit integer
  • T is the character T or space (\x20)
  • hh is the hour in 24 hour format, as an 2 digit integer
  • mm is the minute as an 2 digit integer
  • ss.s is the second, either as an 2 digit integer or as a floating point with 2 digits followed by a period followed by one or more digits.
  • Z is the character Z (indicating timezone Z, UTC+00:00)
  • X is either a plus (+) or minus (-) sign of the timeoffset to UTC
  • aa is the hour of timeoffset to UTC as a 2 digit integer
  • bb is the minute of timeoffset to ITC as a 2 digit integer

format takes a string in the above format or a date-object and returns a string formated as:

  • M D, Y @ h:mm

Where
- M is the full English name of the month
- D is the date of month with a numerical order suffix (1-2 digits)
- Y is the year (1 or more digits)
- h is the hour in 12 hour format (1-2 digits)
- m is the minute (2 digits)

month is an array with the name of the months

ordinal is a function that takes a number as input and return the number with English ordinal suffix.

clock12 is a function that takes hour, minute and second in 24h format and converts it to a string in the US 12h format. The seconds is optional.

单挑你×的.吻 2024-07-20 12:16:15

尝试 http://www.datejs.com/。 它是一个 JavaScript 日期库,具有扩展的 Date.parse 方法和 Date.parseExact 方法,可让您指定格式字符串。
请参阅 DateJS API 文档

Try http://www.datejs.com/. It is a JavaScript Date Library with an extended Date.parse method and a Date.parseExact method, which lets you specify a format string.
See DateJS APIDocumentation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文