How to compare datetime in Javascript? - 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.

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.

Related

Rounding Up to the next date in an array of dates - Javascript

If I had an array of dates, is there a way I could match up another date by rounding up until one is matched?
For example, say I have an array of dates:
"2022-09-15"
"2022-10-10"
"2022-12-01"
And I have a date pulled from the application: "2022-09-29", I want the date to update itself by rounding up until the next upcoming date ("2022-10-10") is selected.
I am unsure how I would round up like I could in mathematics situations.
Assuming your dates are in order, you can iterate through your array starting at the beginning until you find the first date that is bigger than you date provided by the application. In JavaScript, your can do a direct comparison like this:
"2022-09-15" > "2022-10-10" // false
"2022-09-15" < "2022-10-10" // true
Note that this works because of the ordering of the year, month, and day that you have presented. If you wanted to do comparisons where you had day, month, year, you would want to create a Date JavaScript object and do the comparisons that way. You can read more about those here: Compare two dates with JavaScript
But for your use case, a simple loop could look like this:
for(let i = 0; i < array.length; i++) {
if(applicationDate < array[i])
return array[i]
}
You don't necessarily need to "round" the dates up. Incrementing the date and comparing it to every entry in the array until you find a match would take a relatively large amount of time and resources. I prefer a kind of "knock-out" approach to problems like this. Simply rule out everything it can't be until you're left with a single option. In this case, since you specifically need a date that comes after the input date, we can first rule out anything before the input date. We can then take this new list of dates (that we now know are all after the input date) and get the "smallest" one. This will effectively give you the date that is closest to the input date but still after it.
In your question you presented the dates as a list of strings. This isn't a huge deal because this can still be fairly easily accomplished, but the strings must be in a format that JavaScript recognizes as a date, otherwise all comparisons will result in false. Here is a list of the valid date formats.
I personally like to avoid depending on the order of arrays just because it can be hard to maintain and if/when it breaks, it's generally very hard to find that the issue is that the array is out of order (speaking from experience here). For this reason, the code examples provided here will be completely unreliant on the order of the array.
First, let's discuss a solution using Date objects. This is fairly straight forward. The only thing is that you would need to make sure the date being input is in a valid format as discussed previously. Keep in mind the input needs to be converted to a Date object (if it isn't already) because comparisons between date strings and Date objects always return false. To get only dates after the current date, we can use Array.prototype.filter(), and to get the "smallest" date afterwards we can use Math.min.apply() as explained in this Stack Overflow answer.
var dates = [
new Date("2022-09-15"),
new Date("2022-10-10"),
new Date("2022-12-01")
];
var inputDate = new Date("2022-09-29");
var datesAfter = dates.filter(x => x > inputDate);
var closestDate = new Date(Math.min.apply(null,datesAfter));
console.log(closestDate);
Now for date strings. The idea is largely the same as Date objects. The only difference really is that we can't use Math.min.apply() on date strings. We can however use Array.prototype.reduce() in order to compare all the dates, it's just a bit more involved.
var dates = [
"2022-09-15",
"2022-10-10",
"2022-12-01"
];
var inputDate = "2022-09-29";
var datesAfter = dates.filter(x => x > inputDate);
var closestDate = dates.reduce((a, b) => a > b ? a : b);
console.log(closestDate);

Using Moment.js like PHP's date and strtotime

I'm a typically server side developer feeling a bit like a fish out of water trying to display time values on the front end. How can I get behavior like PHP's date() and strtotime() functions out of moment.js? I just want a unix timestamp to appear in H:i:s format, and vice versa.
So far I've tried the following, from existing example code and the documentation:
moment(timestamp).format(H:i:s);
moment().duration(timestamp).format(H:i:s);
moment.unix(timestamp).format(h:mm:ss);
moment(formatted,'H:i:s');
Not a SINGLE one of which has worked properly. This may get flagged as duplicate since there are plenty of moment.js questions out there, but I don't know whether it's been updates to the library itself or slightly different context, I have not found one existing solution that has worked for me.
Anybody have any suggestions for these two simple tasks?
EDIT:
I've distilled two different problems out of this. One is that functions the moment docs say should work are giving weird values:
moment(1437462000).format('h:mm:ss')
for instance, which should return 7:00:00 utc, returns 10:17:42. This can be fixed in this case by using moment.unix(1437462000).utc().format('h:mm:ss') instead, but this leads into the second problem - the .utc() function seems to get ignored when converting back from a date into a timestamp:
timestamp = moment(formatted,'DD/MM/YYYY H:m:s').utc().unix();
will still return a timezone corrected value (in my case this is incorrect by several hours since the formatted time in question has nothing to do with the client computer) regardless of whether the .utc() function is included or not.
A few things you should realize:
Unix timestamps should always in terms of UTC. They are never adjusted for time zone in numerical form. If they're adjusted for time zone, that's done during the interpretation of the number, not in its representation.
While traditionally a "Unix Timestamp" is in terms of seconds, many environments use milliseconds instead. PHP's date timestamps are based on seconds, while moment and JavaScript's Date object both use milliseconds by default. Using the moment.unix function will let you pass seconds, and is identical to just multiplying the timestamp by 1000.
Moment has two built-in modes, local and UTC. The default mode is local. It doesn't matter what input you provide, if you don't specify UTC, the moment is adjusted to local. To specify UTC, you use the utc function. There are two forms of the function:
moment.utc(input) // parsing form
moment(input).utc() // conversion form
Both forms take some input and result in a moment in UTC mode. The difference is in how the input is interpreted. In either case, if the input value is unambiguous, the result is the same. For strings, that means the input would contain either a Z (from ISO8601), or a UTC-based offset. All other forms are ambiguous. For example, if I pass "2015-11-08 01:23:45", I will get different results depending on whether I interpret that string as local time or as UTC.
For numbers, they are always interpreted as milliseconds in UTC. However, if you use moment(number) without then calling .utc() then the moment is left in local mode, so any output will display as local time.
When you call moment.unix(input), the input is a number of seconds, but the moment is left in local mode. So to display the UTC time, you would use moment.unix(input).utc().
If your pre-recorded timestamps from your other system are in numeric form, but have been adjusted away from UTC, then they are incorrect. You have bad data, and Moment can't help you unless you know specifically how they have deviated and you write code to counteract that.
Moment's formatters are case sensitive. M is months, m is minutes. H is hours on a 24-hour clock, h is hours on a 12-hour clock. Use two consecutive letters when you want to include zero-padding. Example, HH:mm:ss for 13:02:03 vs. h:m:s for 1:2:3.
Moment's X formatter does not care which mode the moment is in. It will always emit seconds in UTC. Likewise, the x formatter returns milliseconds in UTC, as does moment.valueOf().
Also, your last example:
moment.unix(1437462000).utc().format()
Returns "2015-07-21T07:00:00+00:00" - which I believe is the value you expected.
You also get the same original timestamp regardless of which of these you try:
moment.unix(1437462000).utc().format("X") // "1437462000"
moment.unix(1437462000).format("X") // "1437462000"
moment.unix(1437462000).utc().unix() // 1437462000
moment.unix(1437462000).unix() // 1437462000
For anyone who comes in and is still looking for direct PHP equivalents for date() and strtotime(), here are the ones I ended up using. Matching up to php basically means just completely ignoring any kind of local time information by making sure everything is in UTC. That task is a little different between the timestamp->date and date->timestamp cases, though, so you have to be careful.
date()
Converting a timestamp to formatted date without any client timezone correction
var formatted = moment.unix(timestamp).utc().format('h:mm:ss');
strtotime()
Converting a UTC formatted date back to a timestamp without correcting it to local time:
var new_timestamp = moment.utc(formatted_utc,'DD/MM/YYYY H:m:s').format('X')
//where 'DD/MM/YYYY H:m:s' is the formatted date's format, and
//'X' outputs a unix timestamp without milliseconds.
Notes:
Do not use moment() with parenthesis in the calls:
moment().utc(date,format) will return local time values, not your
input.
Moment.js does not like the use of 'i' for minutes in the formatting,
unlike php.

Getting the proper date from forms that are day/month/year

When writing a new date object with a string, one can write it as:
var someDay = new Date("12/01/2012");
This equals December 1st 2012.
However, what if the user has to fill in a date on a website where the format isn't month/day/year, but day/month/year? How would one go about creating a date object with the correct date then?
If you are getting the data as a string from another website, then you need to know the format in which that website provides you the date. There is no way around this because D-M-Y and M-D-Y are indistinguishable; even Y-M-D would be indistinguishable if they used a two-digit format for the year.
This hasn't been tested at all, but at worst the general idea should solve your problem.
var pattern = /^(\d+)\b(\d+)\b(\d+)$/;
if (!pattern.test(dateString))
return null;
var matches = dateString.match(pattern);
if (siteUsesDMY)
return new Date(matches[2], matches[1]-1, matches[0]);
if (siteUsesMDY)
return new Date(matches[2], matches[0]-1, matches[1]);
...
Pattern: This pattern supports any numeric representation of the date, assuming it has a breaking character between each unit. If you need to support a website that doesn't have a breaking character, you would need a different pattern that matched that website's exact format (i.e.: site sends DDMMYYYY, then pattern would be /^(\d{2})(\d{2})(\d{4})$/).
Also fixed the month parameter in date creation, as I just remembered that JavaScript uses 0-11 for months.

How to deserialize JSON text into a date type using Windows 8 JSON.parse?

I'm building a Windows 8 Metro app (aka "Modern UI Style" or "Windows Store app") in HTML5/JavaScript consuming JSON Web Services and I'm bumping into the following issue: in which format should my JSON Web Services serialize dates for the Windows 8 Metro JSON.parse method to deserialize those in a date type?
I tried:
sending dates using the ISO-8601 format, (JSON.parse returns a string),
sending dates such as "/Date(1198908717056)/" as explained here (same result).
I'm starting to doubt that Windows 8's JSON.parse method supports dates as even when parsing the output of its own JSON.stringify method does not return a date type.
Example:
var d = new Date(); // => a new date
var str = JSON.stringify(d); // str is a string => "\"2012-07-10T14:44:00.000Z\""
var date2 = JSON.parse(str); // date2 is a string => "2012-07-10T14:44:00.000Z"
Here's how I got this working in a generic way (though it I'd rather find a format supported out-of-the-box by Windows 8's JSON.parse method):
On the server, I'm serializing my strings using:
date1.ToString("s");
This uses the ISO 8601 date format which is always the same, regardless of the culture used or the format provider supplied (see here for more information).
On the client-side, I specified a "reviver" callback to JSON.parse which looks for dates using a regexp and converts them into a date object automatically.
In the end, the deserialized object will contain actual JavaScript date types and not strings.
Here's a code sample:
var responseResult = JSON.parse(request.responseText, function dateReviver(key, value) {
if (typeof value === 'string') {
var re = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)$/
var result = re.exec(value);
if (result) {
return new Date(Date.UTC(+result[1], +result[2] - 1, +result[3], +result[4],+result[5], +result[6]));
}
});
Hope this helps,
Carl
This is not something that's unique to Windows 8's JSON.parse – it's the by-design behavior of the ECMA standard JSON parser. Therefore, there is (and can be) no "out-of-the-box support" for dates.
Per spec, JSON values can only be a String, Number, Boolean, Array, Object, or null. Dates are not supported. (IMO, this is an oversight on the part of the spec, but it's what we have to live with.)
Since there is no date type, your app has to work out how to handle dates on its own. The best way to handle this is to send dates as ISO 8601 strings (yyyy-MM-dd'T'HH:mm:ss'Z') or as milliseconds since the epoch (Jan 1 1970 00:00:00 UTC). The important part here is to make sure time is in UTC.
If performance is important, I would not use a reviver callback with JSON.parse. I did a lot of testing, and the overhead involved with invoking a function for every single property in your object cuts performance in half.
On the other hand, I was honestly surprised with how well testing a regex against every string value stood up against only parsing known property names. Just make sure you define the regex once, outside the loop!
Obviously, the absolute fastest ways to turn JSON values into Dates is if you know exactly what properties need to be parsed for dates. However, given the surprisingly good performance of the regex-based search methods, I don't think it's worth the extra complexity unless you really need the extra performance.
A note on using ISO strings vs milliseconds since epoch: tested independently, milliseconds wins. In IE, there's no difference, but Firefox really seems to struggle with ISO strings. Also note that the Date constructor takes milliseconds in all browsers. It also takes a the ISO string, but not in IE ≤ 8.

Strange syntax in javascript: 'sth'+ +new Date

I'm reading through a jquery plugin, and find this interesting syntax:
'sth'+ +new Date
It creates a numeric string which the author used for a unique id: sth1237004731731
I'm curious what kind of syntax it is, and if there's some reading materials about it? Thanks!
It's using some side effects of JavaScript's type coercion to build a unique identifier (probably for an element). The confusing part is the +new Date. Here, new Date (or new Date()) returns a Date object. But putting a + or a - in front of this forces the JS interpreter to coerce this value to a Number object, and the way JS does Date > Number is by returning the timestamp (or getTime()).
So this code could be expressed differently like this:
var date = new Date(), // "Mon May 14 2012 10:03:58 GMT-0400 (EST)"
timestamp = date.getTime(), // 1337004238612
identifierString = "sth" + timestamp.toString();
You might reasonably claim that there's no need to be so verbose, so I personally would probably have written this as:
var identifier = "sth" + (new Date()).getTime();
However, please avoid coding things like your example if you ever expect someone might have to maintain your code. If it stopped you in your tracks, it probably will stop a lot of people. Coding style is not merely about expressing intent to the interpreter, but expressing intent to human developers. If the code works in the browser but fails with a syntax error in most experienced developers' heads, you've done it wrong, plain and simple.
This is an interesting use of the unary + operator. Basically, you can break down this expression into three separate parts, splitting at the binary + operator:
"sth", then +, then +new Date.
The first operand of the binary + is just a generic string literal. The second operand uses the unary + operator, which, as the linked standard states, converts its operand to a Number.
Because the new operator has the highest precedence, it "binds tighter" than the unary +, which means new Date will be evaluated first. So the operand of the unary + is, in turn, the result of the expression new Date. Of course, new Date simply creates a blank Date object. As per § 15.9.3.3 new Date():
The [[PrimitiveValue]] internal property of the newly constructed
object is set to the time value (UTC) identifying the current time.
In other words, a new Date will just be a Date object representing the current time. And, in turn, +new Date will convert a blank Date object to a number.
The Short Answer
The specification is long and hard to follow. In short, +new Date returns the UNIX timestamp associated with the current time.
The Long Answer: Following the Spec
The long answer, following the specification, is that the unary + calls ToNumber(GetValue(expr)) where expr is the evaluated operand. GetValue(dateObj) will simply return dateObj, so the expression then becomes ToNumber(dateObj).
The result of ToNumber depends on what the type of the argument is. In the case of an object, it returns ToNumber(ToPrimitive(input argument, hint Number)).
ToPrimitive will, in turn, call the valueOf property of the Date object. That returns a Number, which is the time value associated with the Date object: finally, what we were looking for! Then it goes back up the chain: ToNumber(num) simply returns num.
Of course, from there, the string "sth" and the result of +new Date are concatenated (you can find that in the spec if you so wish), which gives you the result you were looking for.

Categories

Resources