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


当前回答

Date.js很适合这个。

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

其他回答

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

将日期转换为yyyy-mm-dd格式的最简单方法是这样做:

var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
                    .toISOString()
                    .split("T")[0];

工作原理:

new Date("Sun May 11,2014") converts the string "Sun May 11,2014" to a date object that represents the time Sun May 11 2014 00:00:00 in a timezone based on current locale (host system settings) new Date(date.getTime() - (date.getTimezoneOffset() * 60000 )) converts your date to a date object that corresponds with the time Sun May 11 2014 00:00:00 in UTC (standard time) by subtracting the time zone offset .toISOString() converts the date object to an ISO 8601 string 2014-05-11T00:00:00.000Z .split("T") splits the string to array ["2014-05-11", "00:00:00.000Z"] [0] takes the first element of that array


Demo

var date =新日期(“太阳5月11日”); var dateString =新日期(日期。 toISOString()。 斯普利特(“T”)[0]; 游戏机。log (dateString);

注意:

The first part of the code (new Date(...)) may need to be tweaked a bit if your input format is different from that of the OP. As mikeypie pointed out in the comments, if the date string is already in the expected output format and the local timezone is west of UTC, then new Date('2022-05-18') results in 2022-05-17. And a user's locale (eg. MM/DD/YYYY vs DD-MM-YYYY) may also impact how a date is parsed by new Date(...). So do some proper testing if you want to use this code for different input formats.

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

只需利用内置的toISOString方法,将您的日期转换为ISO 8601格式:

let yourDate = new Date()
yourDate.toISOString().split('T')[0]

yourDate是你的日期对象。

编辑:@exbuddha在评论中写了这个来处理时区:

const offset = yourDate.getTimezoneOffset()
yourDate = new Date(yourDate.getTime() - (offset*60*1000))
return yourDate.toISOString().split('T')[0]
new Date(new Date(YOUR_DATE.toISOString()).getTime() - 
                 (YOUR_DATE.getTimezoneOffset() * 60 * 1000)).toISOString().substr(0, 10)