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


当前回答

我有一个关于这个问题的提纲

dateInstance.toLocaleDateString().replaceAll("/", "-").split("-").reverse().join("-");

其他回答

格式化并从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));

你可以:

函数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/

2020的答案

你可以使用本地的. tolocaledatestring()函数,它支持一些有用的参数,如区域设置(选择MM/DD/YYYY或YYYY/MM/DD格式),时区(转换日期)和格式详细选项(例如:1 vs 01 vs一月)。

例子

const testCases = [ new Date().toLocaleDateString(), // 8/19/2020 new Date().toLocaleString(undefined, {year: 'numeric', month: '2-digit', day: '2-digit', weekday:"long", hour: '2-digit', hour12: false, minute:'2-digit', second:'2-digit'}), new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}), // 08/19/2020 (month and day with two digits) new Date().toLocaleDateString('en-ZA'), // 2020/08/19 (year/month/day) notice the different locale new Date().toLocaleDateString('en-CA'), // 2020-08-19 (year-month-day) notice the different locale new Date().toLocaleString("en-US", {timeZone: "America/New_York"}), // 8/19/2020, 9:29:51 AM. (date and time in a specific timezone) new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"}), // 09 (just the hour) ] for (const testData of testCases) { console.log(testData) }

注意,有时要以特定的格式输出日期,必须找到与该格式兼容的区域设置。 您可以在这里找到本地示例:https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all

请注意locale只是改变格式,如果你想将特定日期转换为特定国家或城市的等效时间,那么你需要使用timezone参数。

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

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

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));