JS UTC timestamp behaviour - javascript

I'm confused about how this time conversion works. I have timestamp 1462060800000 which when I turn in to date correctly becomes:
Sun May 01 2016 02:00:00 GMT+0200 (Central European Summer Time)
but then when I want to get the month with const startMonth = start.getUTCMonth() I get 4 instead of 5. Why is this happening and what do I need to do to get the correct month?
const timestamp = 1462060800000
const start = new Date(timestamp)
console.log(start) // Sun May 01 2016 02:00:00 GMT+0200 (Central European Summer Time)
const startYear = start.getUTCFullYear()
const startMonth = start.getUTCMonth()
console.log(startMonth) // 4

getUTCMonth() returns zero-based months. 4 is correct. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCMonth.

I get it it's actually a month index that starts with 0.

The getUTCMonth() returns the month of the specified date according to universal time, as a zero-based value (where zero indicates the first month of the year).
From the docs see Date.prototype.getUTCMonth()

The getUTCMonth() method, like getMonth(), has a zero (0) count. This means that the period will be like this - 0 and 11. To get the desired month, you need to add +1:
const startMonth = start.getUTCMonth() + 1;
Loot it.
const timestamp = 1462060800000;
const start = new Date(timestamp);
console.log(start); // Sun May 01 2016 02:00:00 GMT+0200 (Central European Summer Time)
const startYear = start.getUTCFullYear();
const startMonth = start.getUTCMonth() + 1;
console.log(startMonth);

Related

What type of date strings are these in JS?

I get a date string as Fri Sep 17 2021 11:50:59 GMT-0400 (Eastern Daylight Time) from one place. I get it from 2021-09-17T11:50:59-04:00 in a second place.
I want to convert the first format to the second.
I am doing this in a crazy way, so I am thinking there must be a better one.
var d = new Date(`Fri Sep 17 2021 11:50:59 GMT-0400 (Eastern Daylight Time)`);
var iso = d.toISOString();
var time = d.toTimeString();
console.log(iso);
console.log(time);
var [date] = iso.split('T')
var [,localTime, timezone] = time.match(/([^ ]+) GMT([^ ]+)/);
var timezoneWithColon = timezone.replace(/(-*[0-9]{2,2})([0-9]{2,2})/,"$1:$2")
var desiredFormat = '2021-09-17T11:50:59-04:00';
var convertedFormat = `${date}T${localTime}${timezoneWithColon}`;
console.log(desiredFormat)
console.log(convertedFormat)
console.log(desiredFormat === convertedFormat);
The fiddle is over at https://jsfiddle.net/Dave_Stein/8tLv2g4j/.
2021-09-17T11:50:59-04:00 is an ISO-8601 date string.
toISOString should work, however it will convert the time to UTC. If you want this to format in your current timezone, you'll have to use a library such as date-fns:
import { formatISO } from 'date-fns'
formatISO(new Date(`Fri Sep 17 2021 11:50:59 GMT-0400 (Eastern Daylight Time)`))
// prints '2021-09-17T11:50:59-04:00'

Let value changes out of nowhere

Can someone please explain to me, why start and end variables print to console different values for these loggers?
I get printed out:
start1 = Mon Feb 17 2020 10:00:00 GMT+0100 (Central European Standard Time)
end1 = Mon Feb 17 2020 11:30:00 GMT+0100 (Central European Standard Time)
start2 = Mon Feb 17 2020 11:30:00 GMT+0100 (Central European Standard Time)
end2 = Mon Feb 17 2020 11:30:00 GMT+0100 (Central European Standard Time)
I want to add, that the code I presented is in some method of course, and the names start and end don't interfere with other variable names.
let start = this.service.getDateTime(
eventFromUi.start_date,
eventFromUi.start_time_hour,
eventFromUi.start_time_minute
);
console.log("start1 = " + start);
let end = this.service.getDateTime(
eventFromUi.start_date,
eventFromUi.end_time_hour,
eventFromUi.end_time_minute
);
console.log("end1 = " + end);
console.log("start2 = " + start);
console.log("end2 = " + end);
EDIT:
The getDateTime() method returns object of TypeScript ootb type Date.
I used Chrome debugger to look into this, and I see that when I first execute the getDateTime() method, I get value Mon Feb 17 2020 10:00:00 GMT+0100 (Central European Standard Time) returned and assigned to let start.
Then the method getDateTime() is executed again and retuns value Mon Feb 17 2020 11:30:00 GMT+0100 (Central European Standard Time), and this value gets assigned to both start and end variables.
How does this happen?
EDIT2:
Function getDateTime:
getDateTime(dateWithoutTime: Date, hour: number, minute: number): Date {
let date = dateWithoutTime;
console.log(date);
console.log(hour);
console.log(minute);
date.setHours(hour);
date.setMinutes(minute);
return date;
}
This is happening because you're dealing with object references.
getDateTime(dateWithoutTime: Date, hour: number, minute: number): Date {
let date = dateWithoutTime;
// date is now a copy of the *reference* to the same object that
// dateWithoutTime is a reference to. In other words: it is pointing
// to the same object in memory
date.setHours(hour);
date.setMinutes(minute);
// since date is pointing to the same object as dateWithoutTime, this is
// modifying both date and dateWithoutTime
return date;
}
This also means that in your code, eventFromUi.start_date, start and end are all references pointing to the same Date object.
To solve your problem, make sure you create a clone of dateWithoutTime when it is passed into your function:
getDateTime(dateWithoutTime: Date, hour: number, minute: number): Date {
let date = new Date(dateWithoutTime);
// date is now a reference to a *new Date object* with the same
// date/time/etc. values as dateWithoutTime
date.setHours(hour);
date.setMinutes(minute);
// since date now points to a new object, this is only modifying date
// while leaving dateWithoutTime alone and unchanged
return date;
}

Regular expression to fetch year from date - Javascript

Can somebody please help me construct a regular expression in Javascript to check if year 2017 exists or a year starting with 19 or 20 (century) exists in a given date.
My date format is : Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time).
I tried this but it fails:
var str = "Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time)";
var patt = new RegExp("/^\S{3}[\s]\S{3}[\s]\d{2}[\s]\d{4}$/");
var res = patt.test(str);
Thanks,
Haseena
You can use Date.getFullYear() method.
var d = new Date("Fri Dec 01 1999 00:00:00 GMT-0800 (Pacific Standard Time)");
var year = d.getFullYear();
Here is example you can use.
var str="Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time)";
var patt=/(\w{3}\s){2}\d{2}\s(\d{4})\s(.*)/;
var results = patt.exec(str);
console.log(results);
console.log(results[2]);
The second group is match the year.
The year validation with multiple condition is not quite a regex thingy
If I have understood your question then you can try this:
^[a-zA-Z]{3}\s+[A-Za-z]{3}\s+\d{2}\s+(2017|(?:19\d{2}|20\d{2}))\s+.*
It will only match if the year is 2017
It will match if the year starts with 19
It will match if the year starts with 20
If match is found, then the year can be found in group 1
Explanation
const regex = /^[a-zA-Z]{3}\s+[A-Za-z]{3}\s+\d{2}\s+(2017|(?:19\d{2}|20\d{2}))\s+.*$/gm;
const str = `Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time)`;
let m;
if((m = regex.exec(str)) !== null) {
console.log("Full match ="+m[0]);
console.log("Matched year ="+m[1]);
}
else
console.log("no match found");
With a fixed date format, this is really easy:
First, just extract your year using a regular expression var year = str.match(/^.{11}(\d{4})/)[1]
.match returns an array where the first element is the entire matched string and subsequent elements are the parts captured in parentheses.
After you have this, you can test if year === '2017' or if year.substr(0, 2) === '19'.
There are about a dozen other ways to do this, too.
var myDate = 'Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time)';
function isCorrectYear(dateString) {
var year = dateString.match(/^.{11}(\d{4})/)[1];
if (year === '2017') return true;
}
if (isCorrectYear(myDate)) {
alert("It's the correct year.");
}
Something just occurred to me... "year 2017 exists or a year starting with 19 or 20". Doesn't that cover every year in every date string you are ever likely to encounter? I don't think they had Javascript before the 1900s and I doubt anything any of us will write will still be in use after the year 2100.

Javascript:String to date fails

I want to convert a date, given as yyyy-mm-ddThh:mm:ss to a Javascript Date.
First attemp:
var str = "2013-10-31T18:15:30";
var date = new Date(str)
Returns Thu Oct 31 2013 18:15:30 GMT+0100 (CET).
Second attemp:
var str = "2013-10-31T18:15:30";
var str_parts = str.split("T");
var date_parts = str_parts[0].split("-");
var time_parts = str_parts[1].split(":");
var date = new Date(date_parts[0], date_parts[1], date_parts[2], time_parts[0], time_parts[1], time_parts[2]);
Returns Sun Dec 01 2013 18:15:30 GMT+0100 (CET). Do I miss something? Shouldn't this also return Thu Oct 31 2013 18:15:30 GMT+0100 (CET)? Somehow, the date is incorrect, while the time fits.
The corresponding fiddle: http://jsfiddle.net/4CLAj/2/
In the Date constructor Date(year,month,day,hour,minute,second) the month is zero-based, i.e. January is zero.
So for the second attempt:
var date = new Date(date_parts[0], Number(date_parts[1]) - 1, date_parts[2], time_parts[0], time_parts[1], time_parts[2]);
See http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf section 15.9.1.4

Convert date to end of day

I get time in milliseconds from the server. I convert it to Date and get -
Mon Jul 22 2013 11:16:01 GMT+0200 (W. Europe Daylight Time) as the date in the record.
I want to separate out data of Monday, Tuesday etc into arrays. I am thinking of converting this date to Mon Jul 22 2013 23:59:59 GMT+0200 (W. Europe Daylight Time) and then filter out the records.
How can i change the date to the required end of the day time? or is there an easier way to do this ?
You could always construct a new DateTime object just using the year, month and day properties from the existing date, like so:
var actualDate = new Date(); // 2013-07-30 17:11:00
var endOfDayDate = new Date(actualDate.getFullYear()
,actualDate.getMonth()
,actualDate.getDate()
,23,59,59); // 2013-07-30 23:59:59
For future visitors, just use
var start = new Date();
var end = new Date();
start.setHours(0,0,0,0);
end.setHours(23,59,59,999);
Using http://momentjs.com:
var now = new Date().getTime();
var endOfDay = moment(now).endOf("day").toDate(); // Wed Jan 20 2016 23:59:59 GMT-0800 (PST)
var actualDate = new Date()
var eodDate = new Date(Math.floor(actualDate.getTime()/86400000+1)*86400000 + actualDate .getTimezoneOffset()*60000 - 1000)
where 86400000 are total milliseconds in a day
If two Date Objects are on the same day then they have the same Date String:
new Date('1374488161000').toDateString()
=> "Tue Jul 30 2013"
new Date('13744917610403').toDateString()
=> "Tue Jul 30 2013"
Although a rather naive method of comparing days, it's probably the simplest comparison.

Categories