简体   繁体   中英

get min and max of dates in an object

I'm given this object

{"2017-1-1":true,"2017-1-2":true,"2017-1-3":true} , how can I get the min date and max date? I need the range too. What I did was

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

Which I think is bad code. Any better alternative?

Create DateTime objects that represent the first and last dates in a range.

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

Set the SelectionRange property.

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

–or–

Set the SelectionStart and SelectionEnd properties.

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

You could do something like:

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

Take a look to the Date docs and the Array.map function docs just in case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM