2017-03-18 116 views
0

我給這個對象獲得日期的最小值和最大值的對象

{"2017-1-1":true,"2017-1-2":true,"2017-1-3":true},我怎樣才能得到最小日期和最大日期?我也需要範圍。我做的是

temp = Object.keys(obj[0]).split('-')[2] 
const minDate = Math.min(...temp); 
const maxDate = Math.min(...temp); 
//and then concat year and month to rebuild the date format 

我認爲這是不好的代碼。任何更好的選擇?

+0

如果以「」yyyy-mm-dd「'格式保存日期,生活會容易得多。 – 2017-03-18 06:06:39

+0

什麼是'obj'?你期望'obj [0]'是什麼? – 2017-03-18 06:07:50

回答

0

你可以這樣做:

const obj = { 
    "2017-1-1":true, 
    "2017-1-2":true, 
    "2017-1-3":true 
}; 

/* we get the time in ms here, so we can use it to compare */ 
const dates = Object.keys(obj).map(date => new Date(date).getTime()); 

/* we could use one loop and check each value to 
make this a little bit more performant but I didn't find it relevant here */ 
const minDate = new Date(Math.min(...dates)); 
const maxDate = new Date(Math.max(...dates)); 

看看到Date docsArray.map function docs以防萬一。

+0

不錯。 –

0

創建DateTime對象,表示範圍中的第一個和最後一個日期。

DateTime projectStart = new DateTime(2001, 2, 13); 
DateTime projectEnd = new DateTime(2001, 2, 28); 

設置SelectionRange屬性。

monthCalendar1.SelectionRange = new SelectionRange(projectStart, projectEnd); 

- 或 -

設置SelectionStart和選定結束屬性。

monthCalendar1.SelectionStart = projectStart; 
monthCalendar1.SelectionEnd = projectEnd; 
+0

什麼是SelectionRange? –

+0

DateTime projectStart = new DateTime(2001,2,13); DateTime projectEnd = new DateTime(2001,2,28); – Bunny

相關問題