add or subtract timezone difference to javascript Date - javascript

What is the best approach to add or subtract timezone differences to the targetTime variable below. The GMT timezone values comes from the DB in this format: 1.00 for London time, -8.00 for Pacific time and so on.
Code looks like this:
date = "September 21, 2011 00:00:00";
targetTime = new Date(date);

You can use Date.getTimezoneOffset which returns the local offset from GMT in minutes. Note that it returns the value with the opposite sign you might expect. So GMT-5 is 300 and GMT+1 is -60.
var date = "September 21, 2011 00:00:00";
var targetTime = new Date(date);
var timeZoneFromDB = -7.00; //time zone value from database
//get the timezone offset from local time in minutes
var tzDifference = timeZoneFromDB * 60 + targetTime.getTimezoneOffset();
//convert the offset to milliseconds, add to targetTime, and make a new Date
var offsetTime = new Date(targetTime.getTime() + tzDifference * 60 * 1000);

Simple function that works for me:
adjustForTimezone(date:Date):Date{
var timeOffsetInMS:number = date.getTimezoneOffset() * 60000;
date.setTime(date.getTime() + timeOffsetInMS);
return date
}

If you need to compensate the timezone I would recommend the following snippet:
var dt = new Date('2018-07-05')
dt.setMinutes(dt.getMinutes() + dt.getTimezoneOffset())
console.log(dt)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset
The getTimezoneOffset() method returns the difference, in minutes, between a date as evaluated in the UTC time zone, and the same date as evaluated in the local time zone.
So all you need is to compensate, IN MINUTES

This example shows how to use the local datetime but format it as ISO:
const d = new Date();
let dtOffset = new Date(d.setMinutes(d.getMinutes() - d.getTimezoneOffset()));
// Date in EST and ISO format: "2021-11-30T15:33:32.222Z"
console.log(dtOffset.toISOString());

Typescript version of #alexp answer
adjustForTimezone(d:Date, offset:number):Date{
var date = d.toISOString();
var targetTime = new Date(date);
var timeZoneFromDB = offset; //time zone value from database
//get the timezone offset from local time in minutes
var tzDifference = timeZoneFromDB * 60 + targetTime.getTimezoneOffset();
//convert the offset to milliseconds, add to targetTime, and make a new Date
var offsetTime = new Date(targetTime.getTime() + tzDifference * 60 * 1000);
return offsetTime;
}

Related

hours and minutest to timestamp - Javascript

I have hours and minutes in firebase format (can't change this): 2230
I need to convert this to normal date, year, day and month are current time, only hour and minutes are specifed
var startDate = new Date();
I need to set date something like this:
startDate.setHours(myhours, myminutes, myday, 0);
An easy way to do this is to create a new Date, then just update those values:
const hours = 15; // 24-hour format, 0 = midnight, 15 = 3PM
const minutes = 45;
const d = new Date();
d.setHours(hours);
d.setMinutes(minutes);
d.setSeconds(0);
console.log(d);
This will give you a Date object with the current time (as defined by the client's computer), but with the hours and minutes set to what you specify, and seconds set to 0 (since having 15:45:58 is weird).
To convert the string to variables, just do this:
const [, hours, minutes] = '2230'.match(/(\d{2})(\d{2})/).map(m => parseInt(m));
console.log(hours, minutes);
const d = new Date();
d.setHours(hours);
d.setMinutes(minutes);
d.setSeconds(0);
console.log(d);
Keep in mind that it will assume you are setting it based on GMT (timezone offset +0000). If you want it relative to your time, either change the date object (if you just need its values to match) or shift it by your timezone offset.
const hour = 15;
const minute = 45;
const d = new Date();
d.setHours(hour - (d.getTimezoneOffset() / 60)); // adjust hour to local timezone
d.setMinutes(minute);
d.setSeconds(0);
console.log(d);

Converting a time string to a time value in javascript

I have a string that looks like "01:12:33" which is HH:MM:SS format. How can I convert that to a time value in JS?
I've tried the new Date() constructor and setting the year and day values to 0, then doing getTime(), but I am not having any lucky.
Prefix it with a date:
var hms = "01:12:33";
var target = new Date("1970-01-01T" + hms);
console.log(target);
There target.getTime() will give you the number of milliseconds since the start of the day;
Or, if you need it to be today's date:
var now = new Date();
var nowDateTime = now.toISOString();
var nowDate = nowDateTime.split('T')[0];
var hms = '01:12:33';
var target = new Date(nowDate + 'T' + hms);
console.log(target);
There target.getTime() will give you the number of milliseconds since the epoch.
You can add the following function that does the job for you :
function getDateFromHours(time) {
time = time.split(':');
let now = new Date();
return new Date(now.getFullYear(), now.getMonth(), now.getDate(), ...time);
}
console.log(getDateFromHours('01:12:33'));
To be able to do this, there should be a conversion of the string in HH:MM:SS format to JavaScript time.
Firstly, we can use Regular Expression (RegEx) to properly extract the values in that string.
let timeString = "01:12:33";
Extract values with RegEx
let regExTime = /([0-9]?[0-9]):([0-9][0-9]):([0-9][0-9])/;
let regExTimeArr = regExTime.exec(timeString); // ["01:12:33", "01", "12", "33", index: 0, input: "01:12:33", groups: undefined]
Convert HH, MM and SS to milliseconds
let timeHr = regExTimeArr[1] * 3600 * 1000;
let timeMin = regExTimeArr[2] * 60 * 1000;
let timeSec = regExTimeArr[3] * 1000;
let timeMs = timeHr + timeMin + timeSec; //4353000 -- this is the time in milliseconds.
In relation to another point in time, a reference time has to be given.
For instance,
let refTimeMs = 1577833200000 //Wed, 1st January 2020, 00:00:00;
The value above is is the number of milliseconds that has elapsed since the epoch time (Jan 1, 1970 00:00:00)
let time = new Date (refTimeMs + timeMs); //Wed Jan 01 2020 01:12:33 GMT+0100 (West Africa Standard Time)

My setInterval is not working as expected

I do not know why it does not work?
Can you help me please?
function calcTime(city, offset) {
d = new Date();
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
nd = new Date(utc + (3600000*offset));
return nd.toLocaleString();
}
var Paris =setInterval( function() { calcTime('gmt', '+1'); }, 500 );
I do not get the value of calcTime in the Paris variable
setInterval returns an interval pointer, not the value of the function.
You likely want this instead
function calcTime(city, offset) {
var d = new Date();
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
var nd = new Date(utc + (3600000*offset));
return nd.toLocaleString();
}
var parisTId =setInterval( function() {
document.getElementById("paris").innerHTML=calcTime('gmt', '+1');
}, 500 );
It seems you're trying to get the current time in a place with a particular offset in hours (presumably decimal hours since not all timezone offsets are full hours). You can do that fairly simply using:
// Offset is per javascript timezone offset, i.e. minutes to subtract
// from UTC to get local time, so for a place that is UTC+01:00 use -60
function calcTime(offset) {
var d = new Date();
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() - offset);
return d;
}
Note that using toLocaleString will report the timezone of the users current location, not the timezone that the date has been adjusted for, so you might want to build your own string that has the correct offset (say based on ISO 8601).

Format Date as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

I need to format a date as yyyy-MM-dd'T'HH:mm:ss.SSS'Z' as specified by Parse's REST API for Facebook. I was wondering what the most lightweight solution to this would be.
Call the toISOString() method:
var dt = new Date("30 July 2010 15:05 UTC");
document.write(dt.toISOString());
// Output:
// 2010-07-30T15:05:00.000Z
toISOString() will return current UTC time only not the current local time. If you want to get the current local time in yyyy-MM-ddTHH:mm:ss.SSSZ format then you should get the current time using following two methods
Method 1:
console.log(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString());
Method 2:
console.log(new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000).toISOString());
function converToLocalTime(serverDate) {
var dt = new Date(Date.parse(serverDate));
var localDate = dt;
var gmt = localDate;
var min = gmt.getTime() / 1000 / 60; // convert gmt date to minutes
var localNow = new Date().getTimezoneOffset(); // get the timezone
// offset in minutes
var localTime = min - localNow; // get the local time
var dateStr = new Date(localTime * 1000 * 60);
// dateStr = dateStr.toISOString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // this will return as just the server date format i.e., yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
dateStr = dateStr.toString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
return dateStr;
}
Add another option, maybe not the most lightweight.
dayjs.extend(dayjs_plugin_customParseFormat)
console.log(dayjs('2018-09-06 17:00:00').format( 'YYYY-MM-DDTHH:mm:ss.000ZZ'))
<script src="https://cdn.jsdelivr.net/npm/dayjs#1.9.7/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs#1.9.7/plugin/customParseFormat.js"></script>
Node.js
const offsetInMinutes = 2 * 60 ; //Romanian
const todaysDate = new Date(new Date().getTime() + offsetInMinutes * 60000).toISOString();
You can use javax.xml.bind.DatatypeConverter class
DatatypeConverter.printDateTime
&
DatatypeConverter.parseDateTime

problem with changes GMT( time zone )?

I created a small script to display the time(UTC-+3.5). The problem is there that changes GMT(+4.5, +3.5) in Iran every six months in year, and changes Time is pulled back and forth (Daylight Saving)
How i set yourself clock with change GMT in iran? what do i do? (now GMT in iran is +4.5)
EXAMPLE: my code-jsfiddle
var int = self.setInterval("clock()", 1000);
function clock() {
var d = calcTime('+4.5')
var t = d.toLocaleTimeString();
document.getElementById("clock").innerHTML = t;
}
function calcTime(offset) {
d = new Date();
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
nd = new Date(utc + (3600000 * offset));
return nd;
}
With respect
Fiddle Example
<script type="text/javascript">
var int = self.setInterval("clock()", 1000);
function clock() {
var d = calcTime('+4.5')
var t = d.toLocaleTimeString();
document.getElementById("clock").innerHTML = t;
}
function calcTime(offset) {
d = new Date();
ds = new Date(); // new Daylight Savings Time object
ds.setMonth(9); // Set month to september
ds.setDate(21); // set day to 21st
if(d > ds){ // if current date is past the daylight savings date minus one from the offset
offset = eval(offset - 1);
}
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
nd = new Date(utc + (3600000 * offset));
return nd;
}
</script>
<b id="clock"></b>
This works. It will check if the date is currently past September 21st and if it is it will -4.5 from GMT otherwise 3.5
it is not the cleanest code i've ever written, I just modified yours. however you can see how it is done now.

Categories