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.
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.
This is the timestamp I have: 5fb6995
When I do new Date('5fb6995') Invalid Date gets returned. But when I try converting it online in an online converter, everything works. Why doesn't this work and how can I make it work?
You can convert your hexadecimal timestamp to decimal with parseInt and radix 16.
However your timestamp is in hours or something
const ts = parseInt("5fb6995",16);
console.log(new Date(ts)); // 1970
console.log(new Date(ts*1000)); // still 1973 (Unix TSs are normally in seconds since Epoch - 1970/01/01)
// perhaps you want hh-mm-ss from that UNIX timestamp:
console.log(
new Date(ts * 1000).toISOString().slice(11,-5)
)
your string 5fb6995 is in hexadecimal base, you need to first convert it to decimal:
new Date(parseInt("5fb6995", 16));
Is it safe to use slice like this on ISOString to extract time from it?
new Date().toISOString().slice(11, -8); //08:01
The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
So, no, that particular code is not safe. You'd need to use negative offsets for both to be safe.
If you need it to work regardless of time-substring position within output string, you may stick to : delimiter, using RegExp, though, it probably may be somewhat slower compared to slice() or split():
const [time] = new Date().toISOString().match(/\d{1,2}:\d{1,2}/g)
console.log(time)
I would think there are safer options since
The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long
YYYY-MM-DDTHH:mm:ss.sssZ or
±YYYYYY-MM-DDTHH:mm:ss.sssZ,
respectively). The timezone is always zero UTC offset, as denoted by the suffix "Z".
Whereas toUTCString has only one type of output according to MDN. This may not be correct as seen in the ecma262 where there may be negative dates - the code below should still work
const t1 = new Date().toISOString().split("T")[1].slice(0, -8);
const t2 = new Date().toUTCString().split(" ")[4].slice(0, -3); // safer
const t3 = new Date().toLocaleTimeString("en-GB").slice(0, -3) // if you want user's time
console.log(t1,t2,t3)
// or as deceze suggested in his comment
const pad = num => ("0"+num).slice(-2);
const d = new Date();
const t4 = `${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}`;
console.log(t4)
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
I have this date format:
DAY.month.YEAR (today: 28.06.2011)
I will need a Regular Expression (RegEx) pattern for matching this date format.
Can anyone post a solution for this problem?
Derived from http://www.regular-expressions.info/dates.html:
(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[012])\.(19|20)\d\d
This matches a date in dd.mm.yyyy format from between 01.01.1900 and 31.12.2099. It will, however, still match invalid dates, because validating leap years, for example, can not be done with regex (at least not very easily).
However, a regex is probably unnecessary. Javascript example:
var date = "28.06.2011".split("."); // split up the date by the dots
// parse the components into integers
var day = parseInt(date[0]);
var month = parseInt(date[1]);
var year = parseInt(date[2]);
// if you want the date in a date object, which will fix leap years (e.g. 31.02 becomes 03.03
var date = new Date(year, month - 1, day);
Note that when creating a date object, month starts at zero.
Which method you use depends on what you need this for. If you want to find dates in a text, use the regex. If you simply want to parse the date into a date object, use the second method. Some extra validation is possibly necessary to make sure the date is valid, as the javascript Date object does not care about February having 31 days, it simply wraps over to 3. of March.
If you wish to match the format of the date, than it will be enough to use:
\d\d\.\d\d\.\d\d\d\d
However, as David Hall pointed out in his comment to your question, you will still need to validate the date in your code. Doing this in a regex isn't easy, as you can see from Harpyon answer which - still making a "preliminary check that filter out many wrong possiblities" - also accepts 31.02.2011 as a valid date and misses out on the French revolution (14 July 1789).