I am using Angular 10.
I have a function to parse the date:
convertDateToDb(dateStr) {
let dateStrInput = null;
var parts = dateStr.trim().replace(/ +(?= )/g,'').split(/[\s-\/:]/)
if (parts[0].length === 4) {
//YYYY-MM-DD OR YYYY/MM/DD format
dateStrInput = parts[0] + '/' + parts[1] + '/' + parts[2] + ' 00:00';
} else if (parts[0].length === 2) {
//MM/DD/YYYY or MM-DD-YYYY
dateStrInput = parts[2] + '/' + parts[0] + '/' + parts[1] + ' 00:00';
}
let valDate = Date.parse(dateStrInput);
console.log("Parsed Date ms: " + valDate.toString());
console.log("Parsed Date: " + new Date(valDate).toString());
// The above prints with timezone BST, but correct value
// Tue Jun 30 2020 00:00:00 GMT+0100 (British Summer Time)
if (!valDate) {
return new Date().toISOString().split('T')[0];
}
// Now when I use new Date() with string - "06/30/2020 00:00" or "2020-06-30 00:00"
// This gives output "2020-06-29" if any London /Asia user runs.
return new Date(dateStrInput).toISOString().split('T')[0];
}
When I pass "2020-06-30" or "06/30/2020", it returns correct value (2020-06-30). However, when users in other timezone (London / Asia) passes the same value, the date is returned as 2021-06-29 (previous day).
I am unable to re-produce on Windows 7 by changing my machine's timezone.
- Is there a scratch pad or playground online, where I can change the timezone to test my code?
- What is the change in code I can do to ignore timezone, just read the string value passed and convert it. (The issue is with new Date function, how should I tell him not to use timezone)?
I cleared all the cache of browser and changed my machine timezone to London. I am able to replicate this issue.
Now, after changing the timezone, I went to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset
In its editor I am trying to test:
ddtt = new Date("Tue Jun 30 2020").toISOString().split('T')[0];
console.log(ddtt);
Simple string, no TZ or anything.
How should I use new Date to ignore timezone and give date based on string passed?