Search code examples
javascriptdatetimecomparison

How to compare datetime in Javascript?


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

Target
Need to compare this two given datetime to check if this is a valid datetime inputs.

Im thinking that I could 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(),
so on so forth until I get a non equal comparison, then return.

My question is. . Is that the best case in comparing datetime in Javascript?

Any suggested solutions other than this will be much appreciated. . Thank you in advance.


Solution

  • If you only need to know if one date is before or after another, you can use normal comparison operators:

    if (dateA > dateB) { ... }
    

    (Note that to instantiate Date objects, it is new Date(myDateString), not new date() as in your example.)

    This works because the Date objects will be coerced to the underlying epoch values, which are just numbers representing the count of milliseconds that have passed since Jan 1, 1970, GMT. (Relational comparison uses the result of the operands’ @@toPrimitive or valueOf() functions if available.) As a result, this will be sensitive down to the millisecond, which may or may not be desired. You can control the granularity of the comparison either by making sure the input only includes values up to the hour/minute/whatever OR by doing piecemeal comparisons like you described in your question.

    For more advanced date comparison operations, I highly recommend using a library like Moment.js, because natively there is not much to work with. For example Moment provides methods like

    moment(myDateString).startOf('hour')
    

    which can be very helpful if you need to make comparisons only at a particular level of specificity. But none of the datetime libraries are terribly lightweight, so only use them if you are either doing serverside code or you expect to rely on them extensively. If you only need to do this one comparison, it will be wiser to roll your own solution.