How do I compare date and time in Javascript?

Provided by
var fromDatetime = "10/21/2014 08:00:00";
var toDatetime = "10/21/2014 07:59:59";

Purpose
It is necessary to compare this two given days and times to check if this is a valid date and time input.

I think I can use this solution.
Var fromDatetime = new date ("10/21/2014 08:00:00");
var toDatetime = new date ("10/21/2014 07:59:59");

then compare each segment fromDatetime.getFullYear () to toDatetime.getFullYear (),
fromDatetime.getMonth () to toDatetime.getMonth (),
and so on until I get an unequal comparison and then return.

My question. Is this the best example of comparing datetime in Javascript?

Any suggested solutions other than this would be much appreciated., Thanks in advance.

+3


source to share


1 answer


If you only need to know if one date was before or after another, you can use the usual comparison operators:

if (dateA > dateB) { ... }

      

(Note that this is for creating Date objects new Date(myDateString)

, not new date()

as in your example.)

This works because Date objects will be coerced to base epoch values, which are simply numbers representing the number of milliseconds that have passed since January 1, 1970 GMT. In fact, comparison with any object uses the result of its function valueOf()

. As a result, it will be millisecond sensitive, which may or may not be desirable. You can control the granularity of the comparison either by ensuring that the inputs include values ​​down to the hour / minute / regardless of OR by doing partial comparisons as you described in your question.



For more complex date comparison operations, I highly recommend using a library like Moment.js because there isn't much to do initially. For example, Moment provides methods like

moment(myDateString).startOf('hour')

      

which can be very useful if you only need to make comparisons at a certain level of specificity. But none of the datetime libraries are terribly lightweight, so only use them if you are either running server code or can count on their widespread use. If you only need to make this one comparison, it makes more sense to throw your own solution.

+2


source







All Articles