[英]How to turn an array of date components into a JavaScript date object?
So I have an API endpoint returning dates to me as an array, like this: 因此,我有一个API端点将日期作为数组返回给我,如下所示:
{
date: [
'2016',
'4',
'2',
'10',
'3',
'23'
]
}
What's the easiest / tersest way to turn this into a date object, so that I can sort objects? 将其转换为日期对象以便对对象进行排序的最简单/最有趣的方法是什么? The lack of leading zeros and presence of minutes & hours makes me think it is quite difficult?
缺少前导零以及分钟和小时的存在使我觉得这很困难吗?
使用new Date()
并修正月份(从零开始)。
new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
var date = new Date(object.date[0], object.date[1] - 1, object.date[2], object.date[3], object.date[4], object.date[5]);
You're asking for the easiest way. 您正在寻找最简单的方法。 Then here you are.
那你来了
var obj = { date: [ '2016', '4', '2', '10', '3', '23' ] }; --obj.date[1]; console.log(new Date(...obj.date));
From the MDN article of Date
, the month
argument is an Integer value representing the month, beginning with 0 for January to 11 for December . 在
Date
的MDN文章中, month
参数是一个表示月份的Integer值,从1月的0到12月的11开始 。 This means you need to reduce the actual month's value by 1. 这意味着您需要将实际月份的值减少1。
This solution also uses spread operators . 此解决方案还使用扩展运算符 。
If your array is fixed you can use the following 如果阵列固定,则可以使用以下命令
var dt={ date: [ '2016', '4', '2', '10', '3', '23' ] }; //assuming first component is YYYY, second is MM, third is DD then HH:MM:SS alert(new Date(dt.date[0]+"-"+((dt.date[1] - 1) < 10 ? "0" + (dt.date[1]-1) : (dt.date[1]-1))+"-"+ (dt.date[2] < 10 ? "0" + dt.date[2] : dt.date[2]) + "T" + (dt.date[3] < 10 ? "0" + dt.date[3] : dt.date[3]) + ":" + (dt.date[4] < 10 ? "0"+dt.date[4] :dt.date[4]) +":" + (dt.date[5] < 10 ? "0"+dt.date[5] :dt.date[5])))
Extended solution for sorting an array of "dates"(after converting) using Date.getTime
and Array.sort
functions: 使用
Date.getTime
和Array.sort
函数对“日期”数组(转换后)进行排序的扩展解决方案:
var dates = [ { date: [ '2016','4','2','10','3','23'] }, { date: [ '2016','4','1','10','3','23'] }, { date: [ '2016','4','3','11','3','23'] } ]; dates.sort(function(a,b){ // compound date string in form: "2016,4,2 10:3:23" to pass into Date constructor var aDate_str = a.date.slice(0,3).join() + " " + a.date.slice(3).join(":"), bDate_str = b.date.slice(0,3).join() + " " + b.date.slice(3).join(":"), aTime = (new Date(aDate_str)).getTime(), // getting date as the number of milliseconds bTime = (new Date(bDate_str)).getTime(); return (aTime == bTime)? 0 : ((aTime < bTime)? -1 : 1); }); document.write("<pre>" + JSON.stringify(dates, 0, 4) + "</pre>");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.