I'm trying to do computations on Javascript dates, and the following thing happens:
var date = new Date()
undefined
date * 2
2815580408292
date - 10000
1407790194146
date / 6
234631700691
date + 10000
'Mon Aug 11 2014 13:50:04 GMT-0700 (PDT)10000'
It was going so well until I got to the +, where it turned from performing the operation on the milliseconds to concatenating strings. I need + to perform addition on milliseconds, not string concatenation. I'm doing this weird code-generation thing, so I can't do stuff like date.setTime(date.getTime() + 10000) without extraordinary effort and sullying the codebase. Is there some way of hacking Javascript so that + will add the milliseconds instead of concatenating as strings, or is there some date library that I can use + on its date objects and have it do addition rather than concatenation? I tried date.js but it concatenated too.
You mean like this?
date.getTime()+1000
Related
console.log(new Date().getTime());
I have a silly question: In the modern era, is the length of JS new Date().getTime() always 13? Both JS and Java give time strings of this length.
My issue is that I have a random JS string created with
function generateUniqueID() {
return new Date().getTime() + '' + Math.round(Math.random() * Math.pow(10,6));
}
This string concatenates a Time string with a random number. I need to compare 2 IDs to see which one is for an earlier Date. But the random part of this string isn't always a 6-digit number, so I can't truncate the trailing 6 digits and consider that the time string. To get the time string, I can consider the first 13 digits. That seems to be the Unix Epoch Time string in the modern era.
But is that reliable? When would getTime() start giving 14 digits?
Also, if I look up Unix Epoch Time on Wikipedia, I see a 10-digit number as the current Unix Time, not 13-digit: 1637093681.
https://en.wikipedia.org/wiki/Unix_time
Updated
I see the length changes at this point: 2281-11-20 and 2281-11-21
console.log(new Date('2286-11-20').getTime().toString().length);
console.log(new Date('2286-11-21').getTime().toString().length);
The timestamp is milliseconds since 1970-01-01 00:00:00 UTC (the same as the Unix epoch). Subtract the current timestamp from 10000000000000 to get the number of milliseconds until it overflows to 14 digits, which is 8,362,906,319,000. Then divide this by the number of milliseconds in a year, which is about 31,557,600,000, to get the number of years until it reaches that value.
This is about 265 years.
I have the following methods of obtaining a timestamp:
new Date().valueOf()
new Date().getTime()
Date.parse(new Date())
new Date() * 1
But I'm confused: why am I able to get a timestamp using the last method?
This is because the Date() object can be converted directly to a number (the timestamp), and when applying mathematical operators to it JavaScript converts this for us.
An even quicker way to get the timestamp is to use the Unary Plus:
+new Date();
The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number.
– MDN's Unary Plus documentation.
The same applies with strings "1" * 1 equals 1 because JavaScript automatically converts "1" to a number because of the presence of the multiplication operator (*).
One of the weird things about JavaScript is that if you try and perform an operation between two variables, it will try to convert them to a type where it can perform this operation. But this can happen in different ways, so for example "2" * 2 === 4 is true, but so is "2" + 2 === "22" because it goes to the string version of the + operator first.
When you take a Date and try to do multiply or divide it, JavaScript will understand that as converting the Date to it's numerical timestamp value. Consequently the surprising outcome you see above.
However:
new Date() + 1
Results in "Tue Jul 07 2015 15:20:17 GMT+0100 (GMT Daylight Time)1" because the date can also be treated as a string.
This is one of the many quirks of JavaScript that will be helpful to understand when you run into that weird bug, but you would be well advised to avoid using in your code if you want to be able to understand it at a glance later ( spoiler warning: You do! )
I need a little bit of help with a regular expression to convert a date into milliseconds using regular expressions.
I am not sure what regular expression I need to do this.
Here are a few example dates:
3 dagar, 12:00:46
2 dagar, 8:01:00
1 dag, 11:34:00
0 dagar, 0:04:00
Again, I'd like a regexp that will parse these dates into milliseconds.
Alternatively I could use a library like this, to parse the date. But I have not much experience with that either.
The following regex captures days, hours, minutes and seconds.
I asume that you want the number of milliseconds since 1 Jan 1970 (epoch).
We initialize a Date object with the captured info and extract the milliseconds:
var regexp = /([0-9]*) [a-z]*, ([0-9]*):([0-9]*):([0-9]*)/;
var match = regexp.exec('3 dagar, 12:00:46'); //insert your timespan as text here
var date = new Date(1970, 0, parseInt(match[1]) + 1, match[2], match[3], match[4]);
// var result = Math.floor(date.getTime()/1000); //seconds
var result = date.getTime() - date.getTimezoneOffset() * 60000; //milliseconds
We also need to consider the timezone. The date.getTimezoneOffset() returns the offset in minutes.
Maybe you want to test this in rubular and adjust because it may cause problems if the input does not comply with the format that you provided.
I just found a date format in a javascript document that I have never seen before. It looks like this:
'1978-11-23T00:00:01.000Z'
Can someone explain what that 'T' and 'Z' mean?
Can someone explain what that 'T' and 'Z' mean?
The T is the delimiter between the date and time. The Z is a timezone, specifically timezone "Zulu" (GMT+00:00, e.g., Greenwich mean time). As of the latest specification (ES5), JavaScript has a standard date/time format which is derived from a simplified version of ISO 8601 (although it handles the absence of a timezone differently from the ISO standard). (Prior to ES5, there was no standard string form for dates in JavaScript at all, amazingly.)
How to interpret this date format?
If you're using an engine that implements this part of ES5, you can just pass that string into the Date(value) constructor:
var dt = new Date('1978-11-23T00:00:01.000Z');
If you're using an engine that doesn't yet implement this part of the standard (IE8 or earlier, for instance), you'll have to use a regular expression to break out the individual parts of the string, convert them to numbers, and feed them into the Date(year, month, date, hours, minutes, seconds, ms) constructor, or use an add-on library to parse it for you.
(new Date('2012-12-01')).getMonth() is 10 instead of 11 (getMonth is 0-indexed). I've tested on Firefox, Chrome, and Node.js. Why does this happen?
You are experiencing a timezone issue. Your JS engine interprets the string as UTC, since it was no further specified. From the specification of Date.parse (which is used by new Date):
The String may be interpreted as a local time, a UTC time, or a time in some other time zone, depending on the contents of the String. The function first attempts to parse the format of the String according to the rules called out in Date Time String Format (15.9.1.15). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.
In your timezone, the datetime is Nov 30 2012 19:00:00 GMT-0500 - in November. Use .getUTCMonth() and you would get December. However, never trust Date.parse, every browser does it differently. So if you are not in a restricted environments like Node.js, you always should parse your string (e.g. with regex) and feed it to new Date(Date.UTC(year, month, date, …)).
For Firefox's case, at least, RFC2822 states that date specifications must be separated by Folding White Space. Try (new Date('2012 12 01')).getMonth(); Usage of - as a separator does not appear to be defined.
The error is arising from prefixing the day 01 with 0. Not sure WHY this is, but if you remove the zero before the 1, it gives you the right month (11).
Also, it starts giving the wrong month at October if that means anything.
Short term fix, use 1 instead of 01.