9

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.

Sata
  • 93
  • 1
  • 1
  • 3
  • What the comparison seeks to determine will matter in answering your question. Do you only need to know if the dates are different? If one is earlier than the other? Do you need to consider time zones at all? – Semicolon Oct 21 '14 at 02:18
  • Possible duplicate? Compare dates with JavaScript http://stackoverflow.com/questions/492994/compare-dates-with-javascript –  Oct 21 '14 at 02:19
  • I need to know if the dates are different, at the same time, the best case to do this. . About the timezones, this is not required, but lets just say the givens are on the same timezone setting. – Sata Oct 21 '14 at 02:20

1 Answers1

13

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.

Semicolon
  • 6,793
  • 2
  • 30
  • 38