JS: new Date() 不接受我自己的语言环境中的日期字符串 (d/m/y)

发布于 2024-11-30 19:14:26 字数 251 浏览 1 评论 0原文

我的浏览器(即我的操作系统)应该知道我在澳大利亚以及正确的日期格式是什么。在这种情况下,是 d/m/y,而不是 m/d/y。但是,如果我运行以下代码:

alert(new Date("21/11/1968"))

结果是“Thu Sep 11 1969”。它认为月份是第一位的,并相应地进行调整。

这是为什么呢?答案是始终使用通用格式作为日期函数的输入,还是有办法告诉浏览器期望以我的区域设置格式输入日期?

My browser (ie. my OS) should know I'm in Australia and what the correct date format is. In this case, d/m/y, not m/d/y. However if I run the following code:

alert(new Date("21/11/1968"))

The result is "Thu Sep 11 1969". It is thinking the month comes first and adjusting accordingly.

Why is this? Is the answer to always use a universal format as input to date functions, or is there a way to tell the browser to expect dates input in my locale format?

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

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

发布评论

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

评论(4

别忘他 2024-12-07 19:14:26

将日期字符串转换为可提供预期结果的格式非常简单(“yyyy/mm/dd”或“yyyy-mm-dd”):

new Date("21/11/1968".split('/').reverse().join('/'));

[编辑 2023] 您可能会喜欢这个更通用的方法(使用它@Stackblitz)。

document.querySelector("#result").textContent = `
  DateFromString("2017/03/22", "ymd")\n    => ${
    DateFromString("2017/03/22", "ymd")}
  DateFromString("03/22/2017", "mdy")\n    => ${
    DateFromString("03/22/2017", "mdy")}
  DateFromString("22-03-2017", "dmy")\n    => ${
    DateFromString("22-03-2017 22:22:12", "dmy")}`;

function DateFromString(dateString, format = "ymd") {
  const canNot = `"${
    dateString ?? `[no string given]`}" can not be converted to Date`;
  const ds2Array = ds => ds.split(/[T :\-\/.,]/g)
    .filter(v => !!(v.trim()));
  
  return !dateString ? canNot : canDo();

  function canDo() {
    const mapFormat = [...format].reduce((a, b, i) => (a[b] = i, a), {});
    const dateStr2Array = ds2Array(dateString);
    const datePart = dateStr2Array.slice(0, 3);
    const timePart = dateStr2Array.slice(3);
    let [year, month, date, hours, minutes, seconds, milliseconds] = 
      [ +datePart[mapFormat.y],
        +datePart[mapFormat.m] - 1, 
        +datePart[mapFormat.d], ]
      .concat([...Array(4)].map( (_, i) => +timePart[i] || 0 ) );

    return [year, month, date].filter(u => isNaN(u)).length
      ? canNot 
      : new Date( year, month, date, hours, minutes, seconds, milliseconds );
  }
}
<pre id="result"></pre>

It's pretty simple to convert your date string to a format that will give the expected result ('yyyy/mm/dd' or 'yyyy-mm-dd'):

new Date("21/11/1968".split('/').reverse().join('/'));

[Edit 2023] You may like this more generic method (play with it @Stackblitz).

document.querySelector("#result").textContent = `
  DateFromString("2017/03/22", "ymd")\n    => ${
    DateFromString("2017/03/22", "ymd")}
  DateFromString("03/22/2017", "mdy")\n    => ${
    DateFromString("03/22/2017", "mdy")}
  DateFromString("22-03-2017", "dmy")\n    => ${
    DateFromString("22-03-2017 22:22:12", "dmy")}`;

function DateFromString(dateString, format = "ymd") {
  const canNot = `"${
    dateString ?? `[no string given]`}" can not be converted to Date`;
  const ds2Array = ds => ds.split(/[T :\-\/.,]/g)
    .filter(v => !!(v.trim()));
  
  return !dateString ? canNot : canDo();

  function canDo() {
    const mapFormat = [...format].reduce((a, b, i) => (a[b] = i, a), {});
    const dateStr2Array = ds2Array(dateString);
    const datePart = dateStr2Array.slice(0, 3);
    const timePart = dateStr2Array.slice(3);
    let [year, month, date, hours, minutes, seconds, milliseconds] = 
      [ +datePart[mapFormat.y],
        +datePart[mapFormat.m] - 1, 
        +datePart[mapFormat.d], ]
      .concat([...Array(4)].map( (_, i) => +timePart[i] || 0 ) );

    return [year, month, date].filter(u => isNaN(u)).length
      ? canNot 
      : new Date( year, month, date, hours, minutes, seconds, milliseconds );
  }
}
<pre id="result"></pre>

疧_╮線 2024-12-07 19:14:26

Date 对象非常弱。您无法告诉它需要什么格式。您可以像您所说的那样使用 m/d/y 中的字符串创建它,或者 new Date(year,month,day[,hours,secs,milliseconds]);

The Date object is very weak. You cannot tell it what format to expect. You can create it with a string in m/d/y like you stated, or new Date(year, month, day[, hours, seconds, milliseconds]);

灵芸 2024-12-07 19:14:26

new Date(string_date) 支持以下日期格式:

  1. MM-dd-yyyy
  2. yyyy/MM/dd
  3. MM/dd/yyyy
  4. MMMM dd, yyyy
  5. MMM dd, yyyy

new Date(string_date) supports the following Date formats:

  1. MM-dd-yyyy
  2. yyyy/MM/dd
  3. MM/dd/yyyy
  4. MMMM dd, yyyy
  5. MMM dd, yyyy
雅心素梦 2024-12-07 19:14:26

您需要使用新的日期对象来解析它,例如

const myDate = new Date('Wed Dec 30 2020 00:00:00 GMT-0500 (Eastern Standard Time)')

然后将其转换:

const dateFormatted = myDate.toLocaleDateString("en-US")

You need to parse it using a new date object like

const myDate = new Date('Wed Dec 30 2020 00:00:00 GMT-0500 (Eastern Standard Time)')

Then convert it:

const dateFormatted = myDate.toLocaleDateString("en-US")

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