我有一个日期,格式是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日。我该如何解决这个问题?


当前回答

不幸的是,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);
}

其他回答

这为我工作,以所需的格式(YYYYMMDD HH:MM:SS)获取当前日期:

var d = new Date();

var date1 = d.getFullYear() + '' +
            ((d.getMonth()+1) < 10 ? "0" + (d.getMonth() + 1) : (d.getMonth() + 1)) +
            '' +
            (d.getDate() < 10 ? "0" + d.getDate() : d.getDate());

var time1 = (d.getHours() < 10 ? "0" + d.getHours() : d.getHours()) +
            ':' +
            (d.getMinutes() < 10 ? "0" + d.getMinutes() : d.getMinutes()) +
            ':' +
            (d.getSeconds() < 10 ? "0" + d.getSeconds() : d.getSeconds());

print(date1+' '+time1);

不需要库

纯JavaScript。

下面的例子是从今天开始的两个月:

var d = new Date() d.setMonth(d.getMonth() - 2); var dateString =新的日期(d); console.log('格式化前',dateString, '格式化后',dateString. toisostring ().slice(0,10))

简单地使用这个:

var date = new Date('1970-01-01'); // Or your date here
console.log((date.getMonth() + 1) + '/' + date.getDate() + '/' +  date.getFullYear());

简单又甜蜜;)

这很容易由我的date-shortcode包完成:

const dateShortcode = require('date-shortcode')
dateShortcode.parse('{YYYY-MM-DD}', 'Sun May 11,2014')
//=> '2014-05-11'

最短的

.toJSON().slice(0,10);

var d =新的日期(' 2014年5月11日' +' UTC');//解析为UTC let str = d.toJSON().slice(0,10);//显示为UTC console.log (str);