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


当前回答

你可以使用这个函数更好的格式和易于使用:

function convert(date) {
    const d = Date.parse(date)
    const   date_obj = new Date(d)
    return `${date_obj.getFullYear()}-${date_obj.toLocaleString("default", { month: "2-digit" })}-${date_obj.toLocaleString("default", { day: "2-digit"})}`
}

这个函数将把月份和日期格式化为2位输出

其他回答

Date.js很适合这个。

require("datejs")
(new Date()).toString("yyyy-MM-dd")

我们经常遇到这样的问题。每个解决方案看起来都很独特。但在php中,我们有处理不同格式的方法。在https://locutus.io/php/datetime/strtotime/上有一个php的strtotime函数的端口。 一个小的开源npm包,作为另一种方式:

<script type="module">
import { datebob } from "@dipser/datebob.js";
console.log( datebob('Sun May 11, 2014').format('Y-m-d') ); 
</script>

看到datebob.js

2021年的解决方案使用Intl。

现在所有浏览器都支持新的Intl对象。 您可以通过选择使用所需格式的“区域设置”来选择格式。

瑞典语言环境使用的格式是"yyyy-mm-dd":

// Create a date
const date = new Date(2021, 10, 28);

// Create a formatter using the "sv-SE" locale
const dateFormatter = Intl.DateTimeFormat('sv-SE');

// Use the formatter to format the date
console.log(dateFormatter.format(date)); // "2021-11-28"

使用Intl的缺点:

使用此方法不能“取消格式化”或“解析”字符串 你必须搜索所需的格式(例如在维基百科上),不能使用像“yyyy-mm-dd”这样的格式字符串。

重新格式化日期字符串是相当简单的,例如。

var s = ' 2014年5月11日'; 函数reformatDate(s) { 函数z(n){return ('0' + n).slice(-2)} var月=[‘简’,2月,3月,4月,“可能”,“君”, 7月,8月,9月,10月,11月,12月的]; var b = s.split(/\W+/); 返回b[3] + '-' + z (months.indexOf (b [1] .substr .toLowerCase (0, 3) ())) + '-' + z (b [2]); } console.log (reformatDate (s));

当ES2018滚动时(在chrome中工作),你可以简单地正则化它

(new Date())
    .toISOString()
    .replace(
        /^(?<year>\d+)-(?<month>\d+)-(?<day>\d+)T.*$/,
        '$<year>-$<month>-$<day>'
    )

2020-07-14

或者如果你想要一些非常多功能,没有任何库

(new Date())
    .toISOString()
    .match(
        /^(?<yyyy>\d\d(?<yy>\d\d))-(?<mm>0?(?<m>\d+))-(?<dd>0?(?<d>\d+))T(?<HH>0?(?<H>\d+)):(?<MM>0?(?<M>\d+)):(?<SSS>(?<SS>0?(?<S>\d+))\.\d+)(?<timezone>[A-Z][\dA-Z.-:]*)$/
    )
    .groups

哪一个结果提取了以下内容

{
    H: "8"
    HH: "08"
    M: "45"
    MM: "45"
    S: "42"
    SS: "42"
    SSS: "42.855"
    d: "14"
    dd: "14"
    m: "7"
    mm: "07"
    timezone: "Z"
    yy: "20"
    yyyy: "2020"
}

你可以像这样用replace(…, < d > / < m > /美元\ ' < yy > @ < H >:美元$ < MM > '),在顶部,而不是.match(…)。群体

14/7/'20 @ 8:45