我有一个日期,格式是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);
}

其他回答

函数 myYmd(D){ var pad = function(num) { 变量 s = '0' + 数字; 返回 s.substr(s.length - 2); } var Result = D.getFullYear() + '-' + pad((D.getMonth() + 1)) + '-' + pad(D.getDate()); 返回结果; } var datemilli = new Date('Sun May 11,2014'); document.write(myYmd(datemilli));

如果你不反对使用库,你可以像这样使用Moments.js库:

var now = new Date(); var date弦=当下。 瓦尔·戴斯特时刻。格式(“YYYY-MM-DD HH: mm: ss”); <剧本剧本src = " https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js " > < / >

这段代码改变了DD MM YYYY的顺序

function convertDate(format, date) {
    let formatArray = format.split('/');
    if (formatArray.length != 3) {
        console.error('Use a valid Date format');
        return;
    }
    function getType(type) { return type == 'DD' ? d.getDate() : type == 'MM' ? d.getMonth() + 1 : type == 'YYYY' && d.getFullYear(); }
    function pad(s) { return (s < 10) ? '0' + s : s; }
    var d = new Date(date);
    return [pad(getType(formatArray[0])), pad(getType(formatArray[1])), getType(formatArray[2])].join('/');
}

不需要库

纯JavaScript。

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

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

PHP兼容的日期格式

下面是一个小函数,它可以接受与PHP函数date()相同的参数,并在JavaScript中返回日期/时间字符串。

注意,并不是PHP中的所有date()格式选项都受支持。您可以扩展parts对象来创建缺少的格式令牌

/** * Date formatter with PHP "date()"-compatible format syntax. */ const formatDate = (format, date) => { if (!format) { format = 'Y-m-d' } if (!date) { date = new Date() } const parts = { Y: date.getFullYear().toString(), y: ('00' + (date.getYear() - 100)).toString().slice(-2), m: ('0' + (date.getMonth() + 1)).toString().slice(-2), n: (date.getMonth() + 1).toString(), d: ('0' + date.getDate()).toString().slice(-2), j: date.getDate().toString(), H: ('0' + date.getHours()).toString().slice(-2), G: date.getHours().toString(), i: ('0' + date.getMinutes()).toString().slice(-2), s: ('0' + date.getSeconds()).toString().slice(-2) } const modifiers = Object.keys(parts).join('') const reDate = new RegExp('(?<!\\\\)[' + modifiers + ']', 'g') const reEscape = new RegExp('\\\\([' + modifiers + '])', 'g') return format .replace(reDate, $0 => parts[$0]) .replace(reEscape, ($0, $1) => $1) } // ----- EXAMPLES ----- console.log( formatDate() ); // "2019-05-21" console.log( formatDate('H:i:s') ); // "16:21:32" console.log( formatDate('Y-m-d, o\\n H:i:s') ); // "2019-05-21, on 16:21:32" console.log( formatDate('Y-m-d', new Date(2000000000000)) ); // "2033-05-18"

Gist

以下是formatDate()函数的更新版本和其他示例的要点:https://gist.github.com/stracker-phil/c7b68ea0b1d5bbb97af0a6a3dc66e0d9