JavaScript Date Difference Using Format Yyyy-mm-dd
Preet Kalirona0
Finding date differences in JavaScript Date objects is trivial but it takes a turn when dealing with multiple timezones. Well, that is up for another discussion but for now, let’s consider 2 cases of finding differences between two dates using the below date formats.
Using date format - mm/dd/yyyy & yyyy-mm-dd to find the difference
Difference between using mm/dd/yyyy & yyyy-mm-dd
1234567891011
varstart_date=newDate('12/01/2013'),end_date=newDate(),one_day_in_milliseconds=1000*60*60*24,date_diff=Math.floor((end_date.getTime()-start_date.getTime())/one_day_in_milliseconds);console.log("Result 1 - Date difference between ",end_date," & ",start_date," - ",date_diff);vars_date=newDate('2013-12-01'),date_diff_2=Math.floor((end_date.getTime()-s_date.getTime())/one_day_in_milliseconds);console.log("Result 2 - Date difference between ",end_date," & ",s_date," - ",date_diff_2);
You may notice that the difference between both these ways differs by 1. If this is the case and you’re using the second format [yyyy-mm-dd], then you can solve this using the following technique.
Solution
Difference between 2 dates using yyyy-mm-dd
1234567891011121314
functiongetNewDate(dateString){vardate=dateString?newDate(dateString):newDate(),timezoneOffset=date.getTimezoneOffset();returnnewDate(date.getTime()+timezoneOffset*60*1000*(dateString?1:0));}varstart_date=getNewDate('2013-12-01'),end_date=getNewDate(),one_day_in_milliseconds=1000*60*60*24,date_diff=Math.floor((end_date.getTime()-start_date.getTime())/one_day_in_milliseconds);console.log("Date difference between ",end_date," & ",start_date," - ",date_diff);
Here, we are considering the timezone offset when a new Date object is created using dateString in the format yyyy-mm-dd.
Post a Comment