date off by 1 day due to different timezones in javascript - javascript

my default timezone is (UTC + 8:00) Kuala Lumpur, Singapore and the computations is working fine but when I change my pc timezone to (UTC-6:00) Central Time (US & Canada) the result of is off by 1 day.
In (UTC + 8:00) Kuala Lumpur, Singapore Time the output from this.referenceMilestones[key]) is 2022-10-20 and after using the getRefMileStoneDate function the result is
#result which is correct
refMilestoneDate-- Thu Oct 20 2022 00:00:00 GMT+0800 (Philippine Standard Time)
But in timezone (UTC-6:00) Central Time (US & Canada) , the result if off by one day
#result which is wrong , it is now 19 which is supposed to be 20
refMilestoneDate-- Wed Oct 19 2022 00:00:00 GMT-0400 (Eastern Daylight Time)
Any idea how we can solve this one that the date should be consistent regarding of the timezone ? Thanks for helps and ideas.
#Code
const refMilestoneDate = this.getRefMileStoneDate(calculateFields[i].referenceMilestoneName);
console.log('refMilestoneDate--', refMilestoneDate)
getRefMileStoneDate(key:string):Date{
if (this.referenceMilestones && this.referenceMilestones[key]){
console.log(' ' , this.referenceMilestones[key])
return new Date(this.convertDateStringToYYYYMMDD(this.referenceMilestones[key]));
}
return null;
}
convertDateStringToYYYYMMDD(dateString: any) {
if (dateString) {
const dateObject = new Date(dateString);
return dateObject.toLocaleDateString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '-');
}
return '';
}

JavaScript, especially at the client side, typically assumes you're working in local times. You probably want to work exclusively in UTC via the various UTC methods available in the Date object.
Otherwise, you'll want to look into use a date library such as Luxon which will allow you precise control of time zones both when parsing timestamps and when formatting them for display.

Related

Why does my Date subtracts one day after converting from ISO to UTC

I am creating a todo app where users are selecting from-date and to-date.
The requirement is to display the dates in the format Month Year.
On Load the dates are working as expected
const fromDate = subtractOneYearFromDate(new Date()).toISOString());
const toDate = new Date().toISOString());
function subtractOneYearFromDate(date) {
const dateCopy = new Date(date); //2022-02-13T14:00:48.945Z
dateCopy.setFullYear(dateCopy.getFullYear() - 1); //2023-02-13T14:00:48.946Z
return dateCopy;
}
However, when users are trying to change dates, it looks like the dates are one day off. Suppose I am selecting Mar 2022 from the drop down. I get e[0] only correct. So I am converting this to ISO before calling my API.
What I am trying to achieve is : 2022-03-01T16:00:00.000Z
onChange={(e) => {
console.log("e[0]", e[0]) //Tue Mar 01 2022 00:00:00 GMT+0800 (Singapore Standard Time)
console.log(JSON.stringify(e[0])) //2022-02-28T16:00:00.000Z
console.log(e[0].toUTCString()); //28 Feb 2022 16:00:00 GMT
console.log(e[0].toISOString()); //2022-02-28T16:00:00.000Z
console.log(moment.utc(e[0]).local().toISOString()) //2022-02-28T16:00:00.000Z
}

Having issue calculating timeSince due to timeZone confusion

So I am a little bit confused. the server return date is in UTC ISO format, my local time is CST.
so I use toLocaleString() and then subtract the difference but I get a negative number. I rather use react native library rather than installing new libraries such as moment
export function timeSince(date) {
//date is 2022-11-07T18:36:39.543 which is UTC, not CST
date = date.toLocaleString("en-US", {
timeZone: "CST",
});
// somehow stayed 2022-11-07T18:36:39.543
date = new Date(date);
//Mon Nov 07 2022 18:36:39 GMT-0600 (Central Standard Time)
Mon Nov 07 2022 12:29:21 GMT-0600 (Central Standard Time)
'2022-11-07T18:27:38.03'
var seconds = Math.floor((new Date() - date) / 1000); // -21506
return seconds
}

Convert Javascript Date object to other timezone Date Object

How to convert Javascript Date Object to another timezone but the result must be Date object with the correct timezone
let date = new Date();
console.log(date);
date = date.toLocaleString('en-US', { timeZone: 'America/Vancouver' });
date = new Date(date);
console.log(date);
that gives the following result, the last result line (Date/Time) is correct but the time zone is incorrect which is still GMT-0500 (Colombia Standard Time) but must be GMT-0800 (Pacific Standard Time) timezone
Wed Jan 20 2021 00:14:11 GMT-0500 (Colombia Standard Time)
Tue Jan 19 2021 21:14:11 GMT-0500 (Colombia Standard Time)
You may try this :
let date = new Date();
console.log(date);
date = date.toLocaleString("en-CA", {
timeZone: "America/Vancouver",
timeZoneName: "long",
});
console.log(date);
Output:
Wed Jan 20 2021 09:18:16 GMT+0300 (Arabian Standard Time)
2021-01-19, 10:18:16 p.m. Pacific Standard Time
Once you get the correct TimeZone, you may change how the date and time are displayed by string manipulation if you need too.
Update:
This may not look pretty but i believe it should satisfy the requirements:
let date = new Date().toLocaleString("en-US", {
timeZone: "America/Vancouver",
timeZoneName: "short",
});
let date1 = new Date(date);
//adding a new property to Date object called tz and initializing it to null
Date.prototype.tz = null;
//stting the tz value to the Time zone output from toLocalString
date1.tz = date.slice(date.length - 3);
console.log(date1.toISOString() + " " + date1.tz);
console.log(date);
console.log(typeof date1);
Output:
2021-01-20T09:01:06.000Z PST
1/20/2021, 1:01:06 AM PST
Object
What i've done is create a new property of the object date to replace the built-in time zone property in Date, hence you get an object with a user specified Time zone.

Moment.js Real time with timezone

I need to store an unix value from a Time input.
The problem is that :
// I create a Moment Date from my input :
var date = moment({hour: 10, minute: 00)
// gives this _d : Mon May 04 2015 10:00:00 GMT+0200 (CEST)
// I convert it to unix value
date = date.unix()
// -> 1430726400
moment( date ).format('HH:mm')
// -> "14:25" // Should give me 10:00
// Online conversion unix time gives me : Mon, 04 May 2015 08:00:00 GMT
So how can I keep my 10:00 in memory as unix value using those transformations ?
Per documentation:
moment.unix( date ).format('HH:mm')
I kind of sorted it this way :
// I create a Moment Date from my input :
var date = moment({hour: 10, minute: 00)
// gives this _d : Mon May 04 2015 10:00:00 GMT+0200 (CEST)
// Convert to unix
date = date.toDate();
date = date.getTime();
console.log(moment( date ).format('HH:mm')); // Gives me 10:00
I hope it will keep the good time ? In France the time changes twice a year ( go forward 1 hour, go backwards 1 hour)

Format date time JavaScript

How to format date and time like this in JavaScript ?
March 05, 2012 # 14:30 (UTC - 9:30)
I use this code to calculate EST time :
function getDate() {
var now = new Date();
var utc = now.getTime() + (now.getTimezoneOffset() * 60000);
return new Date(utc + (3600000 * -4));
}
I use the date-time-format that Tats recommended because doing it manually is a huge PIA.
var yourDate = dateFormat(getDate(), "mmmm dd, yyyy # HH:MM) + "(UTC -9:30)";
Keep in mind this isn't Daylight Savings aware.. and you are asking for UTC -9:30 in your format, but your function converts to -4. Also, I believe that now.getTime returns in UTC.. so you can just add your difference there.
JavaScript Date Format
Check out date.js! It's a really powerful little library for working with Dates in JavaScript.
To get today's date in EST, you can do something like...
var today = new Date();
today.toString(); // outputs "Wed Apr 11 2012 15:40:40 GMT-0500 (CDT)"
today.setTimezone("EST");
today.toString(); // outputs "Wed Apr 11 2012 14:40:40 GMT-0500 (CDT)"
Also, its worth mentioning to checkout moment.js. I think the two libraries complement each other.
If you do just
var now = new Date();
document.write(now);
you will get
Wed Mar 14 2012 20:53:06 GMT+0000 (GMT Standard Time)
Link1, Link2.
Is it what you want?

Categories