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.
In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.
To compare two time strings:Get the hour, minute and seconds value from each string. Use the values to create a Date object. Compare the output from calling the getTime() method on the Date objects.
To check if a date is before another date, compare the Date objects, e.g. date1 < date2 . If the comparison returns true , then the first date is before the second, otherwise the first date is equal to or comes after the second.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With