How to convert GMT time to Local time? - javascript

In my application i am getting GMT hour, I want to convert it into Local one.
For example
var dateTime = "10:18:00"; //this am getting as GMT
//these below what i want hour and minute separated with locale time zone
var hour = '15';
var minute = '48';
I want to convert it as local i.e if it is india then IST or if any other country then that country's standard time(Locale time). How to achieve this ?

You can get the localHour using getTimezoneOffset()/60. This is a very hacky way of doing it since you don't have the entire Date object for GMT.
var dateTime = "10:18:00"; // GMT
var hour = dateTime.split(':')[0];
var minute = dateTime.split(':')[1];
var date = new Date(); // UTC
var localHour = hour - date.getTimezoneOffset()/60;
var localMinute = (localHour%1) * 60;
localHour = Math.floor(localHour);
localMinute += parseInt(minute);
if (localMinute >= 60) {
localHour += Math.floor(localMinute/60);
localMinute %= 60;
}
localHour %= 24;
console.log('local hour:', localHour);
console.log('local minute:', localMinute);

Related

Epoch to date UTC+3

I used this code to convert epoch to human readable date
var timestamp = 1293683278;
var date = new Date(timestamp*1000);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
I need to change it to UTC+3 how can i do this ?
Thanks for your help
The Date constructor treats time values as UTC. Date objects only ever represent UTC time, the "local" values produced by toString methods use system settings to determine the offset to use, but that's only for the sake of producing a timestamp, it doesn't change the underlying Date or its time value.
If you want a specific offset, you can choose an appropriate IANA location such as Africa/Nairobi, which is +3 all year round, and produce a timestamp using toLocaleString or Intl.DateTimeFormat, e.g.
console.log(
new Date().toLocaleString('default',{timeZone:'Africa/Nairobi', timeZoneName:'short'})
);
Just curious - but couldn't you just append 3 hours onto your timestamp before formatting it with your existing code. I'm curious if there's some date/calendar subtlety where this wouldn't reliably work.
const THREE_HOURS_IN_MS = 3*60*60*1000;
var date = new Date(timestamp*1000 + THREE_HOURS_IN_MS);
// rest of your code stays unchanged
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
You can use moment.js utcOffset to achieve this easily:
const moment = require("moment");
const timestamp = 1619071948 * 1000;
console.log(moment(timestamp).utcOffset(180).format("YYYY-MM-DDThh:mm:ssZ"));
The offset provided is in minutes
https://momentjs.com/docs/#/manipulating/utc-offset/

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 getTimezoneOffset() into static timezone

I have the problem of trying to convert a GMT timestamp on some json to localtime for use in Highcharts. But because there is a lag between getting the json with the timestamp and when the function runs to get the offset (and there may be more time since the timestamp on the json may not reflect the current time) my time is off a minute or two.
var dayLightSavings = true;
var lastMinute = "2013-05-16 22:09:00";
function convertDateTime(lastMinute){
var a = lastMinute.split(' ');
var d = a[0].split('-');
var t = a[1].split(':');
var epochGMT = Date.UTC(d[0],d[1]-1,d[2],t[0],t[1],t[2]);
var z = new Date();
if(dayLightSavings){ // IF TRUE ADD 60 minutes to clock
var n = z.getTimezoneOffset() + 60;
}else{
var n = z.getTimezoneOffset();
}
var epochLocal = epochGMT - (n * 60000);
return epochLocal;
}
How can I do this so that it gives me a range of numbers that equals a timezone that can be added or subtracted from the epochGMT time?
I was thinking something like a switch case:
switch(x){
case(x >= 0000 && x <= 0000):
epochLocal = epochGMT - 0000;
break;
case etc...
}

Javascript getDate() Method for a Countdown Timer

In Javascript whenever we call the getDate() method a value of 1-31 is returned for the particular day of the month. This creates a problem in my countdown timer when I specify a future date in var goal that is greater than 31 which causes the countdown timer to output '12' instead of the number of days that are actually left until the future date.
function twoDigits(number) {return (number < 10 ? '0' : '') + number};
var goal = "Sun January 01 2012 00:00:01";
goal = new Date(goal);
var now = new Date();
var count = new Date(goal.getTime() - now.getTime());
var day = count.getDate() -1;
var hour = count.getHours()-1;
var format = twoDigits(day) + ":" + twoDigits(hour) + ":" + twoDigits(count.getMinutes()) + ":" + twoDigits(count.getSeconds());
$(function () {
$('#counter').countdown({
image: 'digits.png',
startTime: format
});
});
Any ideas how I could fix this?
function padLeft(str,len,char) {
len=Number(len)||1;
char=String(char)||" ";
for(var i=0;i<len;i++)str=char+str;
return str.substr(str.length-len);
}
//$(document).ready(function() {
var goal = "Sun January 01 2011 00:00:01";
goal = new Date(goal);
var now = new Date();
var count = goal.getTime() - now.getTime();
var sign = count/Math.abs(count);
count = Math.abs(count);
var days = Math.floor(count/(24*60*60*1000));
count -= days*24*60*60*1000;
var hours = Math.floor(count/(60*60*1000));
count -= hours*60*60*1000;
var minutes = Math.floor(count/(60*1000));
count -= minutes*60*1000;
var secs = Math.floor(count/1000);
var startTime = days +":"+ padLeft(hours,2,"0") +":"+ padLeft(minutes,2,"0") +":"+ padLeft(secs,2,"0");
alert(startTime);
/*
$("#counter").countdown({
image: 'digits.png',
startTime: startTime,
format: "dd:hh:mm:ss"
});
*/
//}
This is not an exact fix for your code's issue
but if you want helper methods for dates, take a look at sugar.js it has a host of helper methods, like easily calculating the difference in days between now and a given date.
look at the features page for all date methods
you could use this function for example:
var goal = "Sun January 01 2011 00:00:01";
goal = new Date(goal);
var difference = goal.daysFromNow();
daysFromNow() is already an alias for daysUntil() & daysSince() which are for calculating differences in the past or future, daysFromNow() takes care of the past and future at once :)
and that variable would give you the total amount of days, even if it's more than 31 days.

add or subtract timezone difference to javascript Date

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;
}

Categories