My setInterval is not working as expected - javascript

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).

Related

Countdown changed by changing gmt of system(pc) clock

Hi guys need some help,
here is my code
function getCurrentDateByGMT(finalTimezone){
var now = new Date();
var localTime = now.getTime();
var finalGMT = now.getTimezoneOffset() - finalTimezone;
var localOffset = finalGMT * 60000; // where 60000 is equals to 1 min
return new Date(localTime + localOffset);
}
this function gets the current date by inputed gmt -480 where gmt + 8 multiplied by -60
but whenever i changed my computer timezone the countdown also changed.
after i refresh the browser it went back to normal countdown without changing the timezone.
i wonder why can someone help me with this ? thanks in advance and also for grammar correction you are welcome to edit this question thanks thanks.
also, can someone explain this to me thanks again
update :
okay here's my full code
function getTimeRemaining(endtime,gmt){
var t = Date.parse(endtime) - Date.parse(getCurrentDateByGMT(gmt));
var seconds = Math.floor( (t/1000) % 60 );
var minutes = Math.floor( (t/1000/60) % 60 );
var hours = Math.floor( (t/(1000*60*60)) % 24 );
var days = Math.floor( t/(1000*60*60*24) );
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(hour,minute,second,endtime,gmt){
var locHour = document.getElementById(hour);
var locMinute = document.getElementById(minute);
var locSecond = document.getElementById(second);
if(!endtime){
console.log(false);
}else{
function updateClock(){
var countDown = getTimeRemaining(endtime,gmt);
console.log(countDown);// here is the console that output the image above
if(countDown.total>=0){
locHour.innerHTML = ('0' + countDown.hours).slice(-2);
locMinute.innerHTML = ('0' + countDown.minutes).slice(-2);
locSecond.innerHTML = ('0' + countDown.seconds).slice(-2);
}else{
console.log("happend");
clearInterval(timeinterval);
initializeClock(hour,minute,second,generateTimerPerPeriod(),gmt);
}
}
updateClock(); // run function once at first to avoid delay
var timeinterval = setInterval(updateClock,1000);
}
}
function generateTimerPerPeriod(){
var schedule = [['00:00:00', '11:59:59'],['12:00:00', '15:59:59'],['16:00:00', '19:59:59'],['20:00:00', '23:59:59']];
var currentTime = getCurrentDateByGMT(getTimezone('+8'));
var currentPeriod = new Date(currentTime);
for(var timeCtr = 0; timeCtr < schedule.length ; timeCtr++){
var startDate = schedule[timeCtr][0].split(':');
var endDate = schedule[timeCtr][1].split(':');
if(currentTime > currentPeriod.setHours(startDate[0],startDate[1],startDate[2],0) && currentTime < currentPeriod.setHours(endDate[0],endDate[1],endDate[2],0)){
var periodDate = new Date(currentPeriod.setHours(endDate[0],endDate[1],endDate[2],0));
// console.log(" enddate " +periodDate);
return periodDate;
}
}
return false;
}
function getCurrentDateByGMT(finalTimezone){
var myOldDateObj = new Date();
var myTZO = -480;
var myNewDate=new Date(myOldDateObj.getTime() + (60000*(myOldDateObj.getTimezoneOffset()-myTZO)));
console.log(" newdate "+ myNewDate);
var now = new Date();
var localTime = now.getTime();
var finalGMT = now.getTimezoneOffset() - finalTimezone;
var localOffset = finalGMT * 60000; // where 60000 is equals to 1 min
return new Date(localTime + localOffset);
}
function getTimezone(timezone){
return timezone * (-60);
}
Update :
how about this one ?
function getCurrentTimeGMT8(){
var d = new Date();
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
var now = new Date(utc + (3600000*8));
var hour = addZero(now.getHours());
var min = addZero(now.getMinutes());
var sec = addZero(now.getSeconds());
var tz = "GMT+8";
var time = hour +':'+ min +':'+ sec + " " + tz;
return time;
}
A few things:
The getTime function of the Date object always returns values in terms of UTC, so calling it localTime is incorrect. That means your finalGMT and localOffset values are also incorrect because you're assuming the localTime value has been adjusted for the local offset, and it hasn't. Your code should just be:
Any time you construct a new Date by changing the underlying timestamp (like you do with new Date(localTime + localOffset), and also when you create your myNewDate variable), you're not actually changing the time zone. You're just moving the Date to a different moment in time, which is probably not the one you intended. The Date object will still represent time in the current local time zone, and will still follow the DST transition rules for the current local time zone. If you intended it to represent some other time zone, that can get in the way.
Note that you can still calculate the UTC-based numeric timestamp from the current time via Date.now() (or via Date.UTC with user input values) and adding the desired offset. You just can't then take that timestamp and put it in a Date object unless you intend it to reflect the local time zone. If you need to know the year, month, day, hour, minute, second of that timestamp in any other time zone than the local zone, you'll need a library such as moment.js, or some advanced algorithms of your own.
You asked about changing the time zone in the OS. You should recognize that the effect of this is inconsistent across browsers, versions, and operating systems. Many browsers (such as Chrome) will not pick up the new time zone until the browser process is completely terminated and restarted. However, some browsers (such as IE) will update the time zone without requiring a restart. If you need the user's time zone offset, you shouldn't cache it.
Keep in mind that a number can only represent an offset. A time zone can have more than one offset, either due to daylight saving time, or due to changes over its history. Read "Time Zone != Offset" in the timezone tag wiki.
In your case, your countdown timer is working only with offsets. If that's your intent, then fine. You can certainly take a date, time, and offset as input values. Just don't assume that the current offset from new Date().getTimezoneOffset() will necessarily be the correct offset for ALL dates and times in the user's time zone.

How to change the date in javascript having different timezones

I am saving the date in database in unix-timestamp. I have set the timezone default to:
date_default_timezone_set("America/Los_Angeles");
but in javascript I am changing the timestamp in the following way:
for (var i = 0; i < records.length; i++) {
if (originalData[i].SystemLogsUserAction.TimeStamp == "0") {
records[i].TimeStamp = "";
} else {
records[i].TimeStamp = new Date(originalData[i].SystemLogsUserAction.TimeStamp * 1000);
}
}
return records;
The above code change the time but it is not in timezone that I have mentioned.
Stolen shamelessly from: http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/6016329
// function to calculate local time
// in a different city
// given the city's UTC offset
function calcTime(city, offset) {
// create Date object for current location
d = new Date();
// convert to msec
// add local time zone offset
// get UTC time in msec
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
nd = new Date(utc + (3600000*offset));
// return time as a string
return "The local time in " + city + " is " + nd.toLocaleString();
}
this function is useful to calculate time zone value by providing name of a city/country and offset value

How to get the exact local time of client?

What is the best method to get the clients local time irrespective of the time zone of clients system? I am creating an application and i need to first of all get the exact time and date of the place from where the client is accessing. Even detecting the ip address of client system has a drawback or detecting the time zone of client system may be risky at times. So, is there any way out which could be really reliable and not vulnerable to error because displaying wrong time and date to client is something very embarassing.
In JavaScript? Just instantiate a new Date object
var now = new Date();
That will create a new Date object with the client's local time.
Nowadays you can get correct timezone of a user having just one line of code:
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/resolvedOptions
You can then use moment-timezone to parse timezone like:
const currentTime = moment().tz(timezone).format();
Try
let s= new Date().toLocaleString();
console.log(s);
If you want to know the timezone of the client relative to GMT/UTC here you go:
var d = new Date();
var tz = d.toString().split("GMT")[1].split(" (")[0]; // timezone, i.e. -0700
If you'd like the actual name of the timezone you can try this:
var d = new Date();
var tz = d.toString().split("GMT")[1]; // timezone, i.e. -0700 (Pacific Daylight Time)
UPDATE 1
Per the first comment by you can also use d.getTimezoneOffset() to get the offset in minutes from UTC. Couple of gotchas with it though.
The sign (+/-) of the minutes returned is probably the opposite of what you'd expect. If you are 8 hours behind UTC it will return 480 not -480. See MDN or MSDN for more documentation.
It doesn't actually return what timezone the client is reporting it is in like the second example I gave. Just the minutes offset from UTC currently. So it will change based on daylight savings time.
UPDATE 2
While the string splitting examples work they can be confusing to read. Here is a regex version that should be easier to understand and is probably faster (both methods are very fast though).
If you want to know the timezone of the client relative to GMT/UTC here you go:
var gmtRe = /GMT([\-\+]?\d{4})/; // Look for GMT, + or - (optionally), and 4 characters of digits (\d)
var d = new Date().toString();
var tz = gmtRe.exec(d)[1]; // timezone, i.e. -0700
If you'd like the actual name of the timezone try this:
var tzRe = /\(([\w\s]+)\)/; // Look for "(", any words (\w) or spaces (\s), and ")"
var d = new Date().toString();
var tz = tzRe.exec(d)[1]; // timezone, i.e. "Pacific Daylight Time"
In order to get local time in pure Javascript
use this built in function
// return new Date().toLocaleTimeString();
See below example
function getLocaltime(){
return new Date().toLocaleTimeString();
}
console.log(getLocaltime());
directly like this :
new Date((new Date().setHours(new Date().getHours() - (new Date().getTimezoneOffset() / 60)))).toISOString()
more details in this utility function
function getLocaLTime() {
// new Date().getTimezoneOffset() : getTimezoneOffset in minutes
//for GMT + 1 it is (-60)
//for GMT + 2 it is (-120)
//..
let time_zone_offset_in_hours = new Date().getTimezoneOffset() / 60;
//get current datetime hour
let current_hour = new Date().getHours();
//adjust current date hour
let local_datetime_in_milliseconds = new Date().setHours(current_hour - time_zone_offset_in_hours);
//format date in milliseconds to ISO String
let local_datetime = new Date(local_datetime_in_milliseconds).toISOString();
return local_datetime;
}
Just had to tackle this so thought I would leave my answer. jQuery not required I used to update the element as I already had the object cached.
I first wrote a php function to return the required dates/times to my HTML template
/**
* Gets the current location time based on timezone
* #return string
*/
function get_the_local_time($timezone) {
//$timezone ='Europe/London';
$date = new DateTime('now', new DateTimeZone($timezone));
return array(
'local-machine-time' => $date->format('Y-m-d\TH:i:s+0000'),
'local-time' => $date->format('h:i a')
);
}
This is then used in my HTML template to display an initial time, and render the date format required by javascript in a data attribute.
<span class="box--location__time" data-time="<?php echo $time['local-machine-time']; ?>">
<?php echo $time['local-time']; ?>
</span>
I then used the getUTCHours on my date object to return the time irrespective of the users timezone
The getUTCHours() method returns the hour (from 0 to 23) of the
specified date and time, according to universal time.
var initClocks = function() {
var $clocks = $('.box--location__time');
function formatTime(hours, minutes) {
if (hours === 0) {
hours = 12;
}
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
return {
hours: hours,
minutes: minutes
}
}
function displayTime(time, $clockDiv) {
var currentTime = new Date(time);
var hours = currentTime.getUTCHours();
var minutes = currentTime.getUTCMinutes();
var seconds = currentTime.getUTCSeconds();
var initSeconds = seconds;
var displayTime = formatTime(hours, minutes);
$clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);
setInterval(function() {
if (initSeconds > 60) {
initSeconds = 1;
} else {
initSeconds++;
}
currentTime.setSeconds(initSeconds);
hours = currentTime.getUTCHours();
minutes = currentTime.getUTCMinutes();
seconds = currentTime.getUTCSeconds();
displayTime = formatTime(hours, minutes);
$clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);
}, 1000);
}
$clocks.each(function() {
displayTime($(this).data('time'), $(this));
});
};
I then use the setSeconds method to update the date object based on the amount of seconds past since page load (simple interval function), and update the HTML
The most reliable way I've found to display the local time of a city or location is by tapping into a Time Zone API such as Google Time Zone API. It returns the correct time zone, and more importantly, Day Light Savings Time offset of any location, which just using JavaScript's Date() object cannot be done as far as I'm aware. There's a good tutorial on using the API to get and display the local time here:
var loc = '35.731252, 139.730291' // Tokyo expressed as lat,lng tuple
var targetDate = new Date() // Current date/time of user computer
var timestamp = targetDate.getTime() / 1000 + targetDate.getTimezoneOffset() * 60 // Current UTC date/time expressed as seconds since midnight, January 1, 1970 UTC
var apikey = 'YOUR_TIMEZONE_API_KEY_HERE'
var apicall = 'https://maps.googleapis.com/maps/api/timezone/json?location=' + loc + '&timestamp=' + timestamp + '&key=' + apikey
var xhr = new XMLHttpRequest() // create new XMLHttpRequest2 object
xhr.open('GET', apicall) // open GET request
xhr.onload = function() {
if (xhr.status === 200) { // if Ajax request successful
var output = JSON.parse(xhr.responseText) // convert returned JSON string to JSON object
console.log(output.status) // log API return status for debugging purposes
if (output.status == 'OK') { // if API reports everything was returned successfully
var offsets = output.dstOffset * 1000 + output.rawOffset * 1000 // get DST and time zone offsets in milliseconds
var localdate = new Date(timestamp * 1000 + offsets) // Date object containing current time of Tokyo (timestamp + dstOffset + rawOffset)
console.log(localdate.toLocaleString()) // Display current Tokyo date and time
}
} else {
alert('Request failed. Returned status of ' + xhr.status)
}
}
xhr.send() // send request
From: Displaying the Local Time of Any City using JavaScript and Google Time Zone API
I found this function is very useful during all of my projects. you can also use it.
getStartTime(){
let date = new Date();
var tz = date.toString().split("GMT")[1].split(" (")[0];
tz = tz.substring(1,5);
let hOffset = parseInt(tz[0]+tz[1]);
let mOffset = parseInt(tz[2]+tz[3]);
let offset = date.getTimezoneOffset() * 60 * 1000;
let localTime = date.getTime();
let utcTime = localTime + offset;
let austratia_brisbane = utcTime + (3600000 * hOffset) + (60000 * mOffset);
let customDate = new Date(austratia_brisbane);
let data = {
day: customDate.getDate(),
month: customDate.getMonth() + 1,
year: customDate.getFullYear(),
hour: customDate.getHours(),
min: customDate.getMinutes(),
second: customDate.getSeconds(),
raw: customDate,
stringDate: customDate.toString()
}
return data;
}
this will give you the time depending on your time zone.
Thanks.
Here is a version that works well in September 2020 using fetch and https://worldtimeapi.org/api
fetch("https://worldtimeapi.org/api/ip")
.then(response => response.json())
.then(data => console.log(data.dst,data.datetime));
I needed to report to the server the local time something happened on the client. (In this specific business case UTC provides no value). I needed to use toIsoString() to have the format compatible with .Net MVC but toIsoString() this always converts it to UTC time (which was being sent to the server).
Inspired by the 'amit saini' answer I now use this
function toIsoStringInLocalTime(date) {
return new Date((date.getTime() + (-date.getTimezoneOffset() * 60000))).toISOString()
}
You can also make your own nodeJS endpoint, publish it with something like heroku, and access it
require("http").createServer(function (q,r) {
r.setHeader("accees-control-allow-origin","*")
r.end(Date.now())
}).listen(process.env.PORT || 80)
Then just access it on JS
fetch ("http://someGerokuApp")
.then(r=>r.text)
. then (r=>console.log(r))
This will still be relative to whatever computer the node app is hosted on, but perhaps you can get the location somehow and provide different endpoints fit the other timezones based on the current one (for example if the server happens to be in California then for a new York timezone just add 1000*60*60*3 milliseconds to Date.now() to add 3 hours)
For simplicity, if it's possible to get the location from the server and send it as a response header, you can just do the calculations for the different time zones in the client side
In fact using heroku they allow you to specify a region that it should be deployed at https://devcenter.heroku.com/articles/regions#specifying-a-region you can use this as reference..
EDIT
just realized the timezone is in the date string itself, can just pay the whole thing as a header to be read by the client
require("http").createServer(function (q,r) {
var d= new Date()
r.setHeader("accees-control-allow-origin","*")
r.setHeader("zman", d.toString())
r.end(d.getTime())
}).listen(process.env.PORT || 80)
new Date(Date.now() + (-1*new Date().getTimezoneOffset()*60000)).toISOString()
my code is
function display_c(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('display_ct()',refresh)
}
function display_ct() {
var strcount
var x = new Date()
document.getElementById('ct').innerHTML = x;
tt=display_c();
}
<body onload=display_ct();>
<span id='ct' ></span>
</body>
Try on this way
function timenow(){
var now= new Date(),
ampm= 'am',
h= now.getHours(),
m= now.getMinutes(),
s= now.getSeconds();
if(h>= 12){
if(h>12) h -= 12;
ampm= 'pm';
}
if(m<10) m= '0'+m;
if(s<10) s= '0'+s;
return now.toLocaleDateString()+ ' ' + h + ':' + m + ':' + s + ' ' + ampm;
}
toLocaleDateString()
is a function to change the date time format like toLocaleDateString("en-us")

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

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