A
A
Alexander Wolf2013-07-21 00:39:25
JavaScript
Alexander Wolf, 2013-07-21 00:39:25

Date difference?

Hello. Recently, I fell into a stupor and could not get the time difference in the form of YEAR - MONTH - DAYS - HOURS - MINUTES - SECONDS.
In the input we have a date ( date ). We need to compare with the current time and print the difference. I apologize for the incomprehensible explanation, the head no longer cooks.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
D
Denis Ineshin, 2013-07-21
@mannaro

Moment.js is a great library for working with time. Among other things, it can do all kinds of comparisons of dates with each other. Try it, maybe this is what you need. In addition, it will be able to display the difference in any format you specify. Including in any language.

N
noonesshadow, 2013-07-21
@noonesshadow

both dates (the input date and the current date) must be set in the same time zone
between two dates could translate time, then you may need to add or subtract 1 hour of
the year there are leap years and no
if the approximate value suits, then the difference between the two Date objects - number of milliseconds between them
divided
by 1000 - seconds
by 60000 - minutes
by 3600000 - hours
by 86400000 - day
by 31536000000 - years

A
Amon_Sha, 2013-07-21
@Amon_Sha

That's right, "YEARS - HOURS - MINUTES - SECONDS"? Days, months are not needed?
I would do this:
1) get the date difference in seconds
2) divide by 60: the result is the difference in minutes, the remainder is seconds
3) divide by 60: the result is the difference in hours, the remainder is minutes
4) divide by 24: the result is the difference is in days, the remainder is hours
5) ... here you need to correctly calculate the years (taking into account leap years and multiples of 100 and 400), we get the difference in years, the remainder is days
6) RPOFIT
If you also need months, it will be much more difficult.

N
Nazar Mokrinsky, 2013-07-21
@nazarpc

If I understand correctly:
javascript.ru/Date
There is a list of methods, take setYear/setDate/etc and then get the Unix timestamp (Date.getTime()) of the desired time. Create another object, it will be with the current time by default, take the difference between their Unix timestamps, get the difference between dates in ms. The browser will take care of leap years and other things.

A
Anton, 2013-07-21
@sHinE

It's actually a jQuery plugin, but take a look: github.com/rmm5t/jquery-timeago

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question