我有一个日期,格式是2014年5月11日太阳。如何使用JavaScript将其转换为2014-05-11 ?

函数taskDate(dateMilli) { var d = (new Date(dateMilli) + ")。分割(' '); D [2] = D [2] + ','; 返回[d[0], d[1], d[2], d[3]]。加入(' '); } var datemilli =日期。解析(' 2014年5月11日'); console.log (taskDate (datemilli));

上面的代码给了我相同的日期格式,2014年5月11日。我该如何解决这个问题?


当前回答

这对我来说很有效,如果需要测试,你可以直接将它粘贴到你的HTML中:

<script type="text/javascript">
    if (datefield.type!="date"){ // If the browser doesn't support input type="date",
                                 // initialize date picker widget:
        jQuery(function($){ // On document.ready
            $('#Date').datepicker({
                dateFormat: 'yy-mm-dd', // THIS IS THE IMPORTANT PART!!!
                showOtherMonths: true,
                selectOtherMonths: true,
                changeMonth: true,
                minDate: '2016-10-19',
                maxDate: '2016-11-03'
            });
        })
    }
</script>

其他回答

将日期转换为yyyy-mm-dd格式的最简单方法是这样做:

var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
                    .toISOString()
                    .split("T")[0];

工作原理:

new Date("Sun May 11,2014") converts the string "Sun May 11,2014" to a date object that represents the time Sun May 11 2014 00:00:00 in a timezone based on current locale (host system settings) new Date(date.getTime() - (date.getTimezoneOffset() * 60000 )) converts your date to a date object that corresponds with the time Sun May 11 2014 00:00:00 in UTC (standard time) by subtracting the time zone offset .toISOString() converts the date object to an ISO 8601 string 2014-05-11T00:00:00.000Z .split("T") splits the string to array ["2014-05-11", "00:00:00.000Z"] [0] takes the first element of that array


Demo

var date =新日期(“太阳5月11日”); var dateString =新日期(日期。 toISOString()。 斯普利特(“T”)[0]; 游戏机。log (dateString);

注意:

The first part of the code (new Date(...)) may need to be tweaked a bit if your input format is different from that of the OP. As mikeypie pointed out in the comments, if the date string is already in the expected output format and the local timezone is west of UTC, then new Date('2022-05-18') results in 2022-05-17. And a user's locale (eg. MM/DD/YYYY vs DD-MM-YYYY) may also impact how a date is parsed by new Date(...). So do some proper testing if you want to use this code for different input formats.

format = function date2str(x, y) {
    var z = {
        M: x.getMonth() + 1,
        d: x.getDate(),
        h: x.getHours(),
        m: x.getMinutes(),
        s: x.getSeconds()
    };
    y = y.replace(/(M+|d+|h+|m+|s+)/g, function(v) {
        return ((v.length > 1 ? "0" : "") + z[v.slice(-1)]).slice(-2)
    });

    return y.replace(/(y+)/g, function(v) {
        return x.getFullYear().toString().slice(-v.length)
    });
}

结果:

format(new Date('Sun May 11,2014'), 'yyyy-MM-dd')
"2014-05-11

不幸的是,JavaScript的Date对象有很多陷阱。任何基于Date内置toISOString的解决方案都必须打乱时区,这一点在这个问题的其他一些答案中已经讨论过。表示ISO-8601日期(没有时间)的干净解决方案是由Temporal提供的。来自Temporal提案的PlainDate。从2021年2月起,你必须选择最适合你的变通方法。

使用日期与香草字符串连接

假设您的内部表示基于Date,您可以手动执行字符串连接。下面的代码避免了Date的一些缺陷(时区、从零开始的月份、缺少2位数格式),但可能还存在其他问题。

function vanillaToDateOnlyIso8601() {
  // month May has zero-based index 4
  const date = new Date(2014, 4, 11);

  const yyyy = date.getFullYear();
  const mm = String(date.getMonth() + 1).padStart(2, "0"); // month is zero-based
  const dd = String(date.getDate()).padStart(2, "0");

  if (yyyy < 1583) {
    // TODO: decide how to support dates before 1583
    throw new Error(`dates before year 1583 are not supported`);
  }

  const formatted = `${yyyy}-${mm}-${dd}`;
  console.log("vanilla", formatted);
}

使用Date和helper库(例如formatISO from Date -fns)

这是一种流行的方法,但您仍然被迫将日历日期作为date来处理,它表示

一个独立于平台格式的单一时刻

下面的代码应该可以完成这项工作:

import { formatISO } from "date-fns";

function dateFnsToDateOnlyIso8601() {
  // month May has zero-based index 4
  const date = new Date(2014, 4, 11);
  const formatted = formatISO(date, { representation: "date" });
  console.log("date-fns", formatted);
}

找到一个正确表示日期和时间的库

我希望有一个干净的、经过实战考验的库,它能带来自己设计良好的日期-时间表示。对于这个问题中的任务,一个很有希望的候选者是@js-joda/core中的LocalDate,但是这个库不如date-fns活跃。在处理一些示例代码时,在添加可选的@js-joda/timezone后,我也遇到了一些问题。

然而,核心功能在我看来非常干净:

import { LocalDate, Month } from "@js-joda/core";

function jodaDateOnlyIso8601() {
  const someDay = LocalDate.of(2014, Month.MAY, 11);
  const formatted = someDay.toString();
  console.log("joda", formatted);
}

用时间提案填充实验

不建议在生产环境中使用,但是如果你愿意,你可以导入future:

import { Temporal } from "proposal-temporal";

function temporalDateOnlyIso8601() {
  // yep, month is one-based here (as of Feb 2021)
  const plainDate = new Temporal.PlainDate(2014, 5, 11);
  const formatted = plainDate.toString();
  console.log("proposal-temporal", formatted);
}

如果你使用momentjs,现在它们包含了一个YYYY-MM-DD格式的常量:

date.format(moment.HTML5_FMT.DATE)

这里有一种方法:

var date = Date.parse('Sun May 11,2014');

function format(date) {
  date = new Date(date);

  var day = ('0' + date.getDate()).slice(-2);
  var month = ('0' + (date.getMonth() + 1)).slice(-2);
  var year = date.getFullYear();

  return year + '-' + month + '-' + day;
}

console.log(format(date));