我有一个日期,格式是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对象上使用UTC版本的日、月、年函数,因为这将以UTC时间显示,并避免在某些时区出现差一的错误。

更好的是,使用Moment.js日期库来进行这种格式设置。

其他回答

你可以:

函数formatDate(日期){ var d = new Date(日期), 月= " + (d.getMonth() + 1) ", day = " + d.getDate(), year = d.g getfullyear (); 如果(月。长度< 2) 月= '0' +月; 如果一天。长度< 2) Day = '0' + Day; 返回[年,月,日].join('-'); } console.log(formatDate('Sun May 11,2014'));

使用的例子:

console.log(formatDate('Sun May 11,2014'));

输出:

2014-05-11

JSFiddle的演示:http://jsfiddle.net/abdulrauf6182012/2Frm3/

格式化并从hashmap数据中查找最大值和最小值:

var obj = {"a":'2001-15-01', "b": '2001-12-02' , "c": '2001-1-03'}; function findMaxMinDate(obj){ let formatEncode = (id)=> { let s = id.split('-'); return `${s[0]+'-'+s[2]+'-'+s[1]}`} let formatDecode = (id)=> { let s = id.split('/'); return `${s[2]+'-'+s[0]+'-'+s[1]}`} let arr = Object.keys( obj ).map(( key )=> { return new Date(formatEncode(obj[key])); }); let min = new Date(Math.min.apply(null, arr)).toLocaleDateString(); let max = new Date(Math.max.apply(null, arr)).toLocaleDateString(); return {maxd: `${formatDecode(max)}`, mind:`${formatDecode(min)}`} } console.log(findMaxMinDate(obj));

使用joda-js并完成它:

import { DateTimeFormatter, LocalDateTime } from 'js-joda'

const now = LocalDateTime.now()
now.format(DateTimeFormatter.ofPattern('yyyyMMdd-HH:mm:ss'))
// Outputs: 20221104-09:25:09 according to your timezone (mine is 'America/New_York'

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