简体   繁体   中英

How to convert a string eg: '8/31/2020' to a date, and substract it from todays date to find number of days that have passed in JavaScript

In my MVC project, I am trying to get the start date value from a cookie which returns a string m/dd/yyyy and I am trying to figure out how to find the number of days that have passed from the string date until now in JavaScript so the function occurs on the client side in the view.

My javascript is incredibly rusty.

currently my cookie value returns string '8/31/2020'. How can I convert this to a javascript date and find how many days have passed?

Any help will be greatly appreciated!

Considering that cookieDate is always in the past, this is the shortest answer:

const cookieDate = new Date('8/31/2020'); const today = new Date();
const diffDays = Math.ceil((today - cookieDate)/(1000*60*60*24)); // diffDays = 22

If you care about daylight saving time check this answer .

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