I want to calculate date difference in days, hours, minutes, seconds, milliseconds, nanoseconds, how can I do it? Please suggest.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
Another solution is convert difference to a new Date object and get that date's year(diff from 1970), month, day etc.
So difference is like "3 years and 6 months and 4 days". If you want to take difference in a human readable style, that can help you.
With momentjs it's simple:
Expressions like "difference in days" are never as simple as they seem. If you have the following dates:
the difference in time is 2 minutes, should the "difference in days" be 1 or 0? Similar issues arise for any expression of the difference in months, years or whatever since years, months and days are of different lengths and different times (e.g. the day that daylight saving starts is 1 hour shorter than usual and two hours shorter than the day that it ends).
Here is a function for a difference in days that ignores the time, i.e. for the above dates it returns 1.
This can be more concise:
This is how you can implement difference between dates without a framework.
Code sample taken from here.