I can't seem to find what is causing this. I checked the url again and again and I can't seem to find what is wrong with it.
function setTime() {
min = $("#minutes").val();
hour = $("select").val();
odG = $("#odGodina").val();
doG = $("#doGodina").val();
dat = $("#datepicker").val();
dat = dat.split("/"); //mm.dd.YYYY
vreme = new Date(dat[2], dat[0], dat[1], hour, min);
sendInput(vreme);
}
function sendInput(time) {
console.log(time.getTime());
var url = "https://maps.googleapis.com/maps/api/timezone/json?location="+lat+","+lngt+"×tamp="+time.getTime()+"&sensor=false";
var testResenje = $.ajax({
url: url,
}).done(function(response) {
offset = response.rawOffset / 3600 + response.dstOffset / 3600;
sendResponse();
console.log(offset);
});}
The url that gets build is:
https://maps.googleapis.com/maps/api/timezone/json?location=44.7220401,21.175114500000063×tamp=1455189900000&sensor=false
Is there a problem with the number of characters long and lat have?
Or is my function order bad?
EDIT: Turns out if i have one less character in timestamp it works. Does that mean I can't use current time?
Google timezoneapi expects timestamp as seconds as how unix timestamp represents not milliseconds.
timestamp specifies the desired time as seconds since midnight, January 1, 1970 UTC.
ref: https://developers.google.com/maps/documentation/timezone/intro.
Related
I am using a counter library that will count down the amount of time allowed for user for reading a book section, that library will accept a milliseconds value to work.
Now i have function for getting the allowed time from api which contain the following code :-
// api request -> var data.created_at = contain the section read request created_at date/time.
var readAllowedurationInHr = 2;
var readAllowedDurationInDay = null;
var createdAt = new Date(data.created_at);
if (readAllowedDurationInDay) {
createdAt.setDate(createdAt.getDate() + readAllowedDurationInDay);
var diffInMilliseconds = createdAt.getTime() - Date.now();
}
if (readAllowedurationInHr) {
createdAt.setDate(createdAt.getHours() + readAllowedurationInHr);
var now = new Date();
var diffInMilliseconds = createdAt.getTime() - now.getTime();
}
setCounterValue(diffInMilliseconds);
The code for getting the days difference "if (readAllowedDurationInDay)" is working, but for handling the hour difference "if (readAllowedurationInHr)" it show in the counter a count down starting from 16 days.
How can i get the difference in hours between dates in millisecond unit ?
I'm trying to create a countdowntimer in Javascript. There are a lof of examples on the internet. I'm trying to adjust these to my own needs. I want a countdown timer that, when started, countsdown to the whole hour. For example, if I run the code at 13:15 it wil count down to 14:00.
The problem I have is getting the time to countdown to.
var cd = new Date("Jan 5, 2021 15:37:25").getTime();
In the above example you have a defined date. I'm trying to change this to a time to the first upcoming hour. Below is what I have:
var countdowndate = newDate("cd.getMonth, cd.getYear (cd.getHour + 1):00:00").getTime();
This isn't working. What am I doing wrong here? Any help is appreciated.
Here's a very expressive way of solving this:
Get the current time stamp, floored to the last full minute.
Get how many full minutes remain until the next hour, transform to milliseconds.
Sum up the results of 1 and 2.
function getBeginningOfNextHour() {
const msPerMinute = 60 * 1000;
const currentDate = new Date();
const currentDateTimestampRoundedToMinute = Math.floor(+currentDate / msPerMinute) * msPerMinute;
const msUntilNextHour = (60 - currentDate.getMinutes()) * msPerMinute;
return new Date(currentDateTimestampRoundedToMinute + msUntilNextHour);
}
console.log(getBeginningOfNextHour());
I had two ical format timestamps and I want to convert them to normal time first and then to unix time.
Here this is the function I've been using to convert normal time to unix timestamp:
var normal_to_unix = function (date_string) {
var date = new Date(date_string);
return date.getTime() / 1000;
}
This function is fine since date is already in UTC and I need not do any conversions.
Now this is the function I've been using to convert ical time to unix time. The ical time in my case is like "20180603T150000Z".
var ics_to_unix = function (ics_string) {
var year = ics_string.slice(0, 4);
var month = ics_string.slice(4, 6);
var date = ics_string.slice(6, 8);
var hours = ics_string.slice(9, 11);
var minutes = ics_string.slice(11, 13);
var seconds = ics_string.slice(13, 15);
var milliseconds = 0;
console.log(year, month, date, hours, minutes, seconds, milliseconds); // This is example output 2018 06 03 15 00 00 0
return normal_to_unix((new Date(year, month, date, hours, minutes, seconds, milliseconds)).toDateString())
}
Now the problem is I'm getting the same unix time for "20180603T150000Z" and "20180603T160000Z" which are supposed to give different timestamps and it is 1530576000 for both of them.
Is there anything that I'm missing ? Thanks in advance.
Please have a look at this for live example
Several points here:
The toDateString() method returns the date portion of a Date object in human readable form in American English. For your example it is `Tue Jul 03 2018', perhaps that is not what you want.
new Date creates date in your local timezone, which could play well if you use it together with toString(), which will also return the string for date in your local timezone. But it will be subject to daylight saving changes, so I'd avoid using that method.
Another thing I'd like to avoid converting back and forth between strings and dates, since it does a lot of unnecessary computations.
I'd suggest to use the following:
var ics_to_unix = function (ics_string) {
var year = parseInt(ics_string.slice(0, 4));
var month = parseInt(ics_string.slice(4, 6)) - 1; // Jan is 0
var date = parseInt(ics_string.slice(6, 8));
var hours = parseInt(ics_string.slice(9, 11));
var minutes = parseInt(ics_string.slice(11, 13));
var seconds = parseInt(ics_string.slice(13, 15));
return Date.UTC(year, month, date, hours, minutes, seconds) / 1000;
}
I have added explicit conversion of strings to numbers, adjusted the month to match what is used in javascript and also removed the extra call.
I've spent a lot of time trying to understand the timezones. But i'm still confused.
Design:
1) Server in a different time zone than client.
2) I got the following Info in API call:
/api/config/v1/system/time
{
"timeZoneOffset": -18000000, (milli sec)
"serverTimeUTC": 1485332569157,
"serverTime": "Wed Jan 25 03:22:49 EST 2017",
"timeZone": "Eastern Standard Time"
}
3) I have no access on the server. (Can't really change any code there!)
4) I have a complete access on client side. (Javascript)
Problem/Requirement:
I want to take clients time (PST, CST etc) and send it in the corresponding server time. (Whatever timezone the server is in) (Not necessarily UTC).
My code:
I've attempted the following but still confused as where I'm going:
getServerTimeZone: function(newTime){
var _this = this;
$.ajax({
url: '/api/config/v1/system/time'
})
.done(function(data) {
if(!newTime){
newTime = new Date();
}
//Get Server Timezone and offset
//Offset is in milli sec. Converting it to hours
var serverTimeOffset = data.timeZoneOffset / (60 * 60 * 1000);
// Get current timezone offset for host device
var x = new Date();
var clientCurrentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
//Calculate the difference
var actualOffset = Math.abs(clientCurrentTimeZoneOffsetInHours - serverTimeOffset);
//Format actual time in relative to server time
serverTime = moment.utc(newTime).zone(actualOffset).format('MM/DD/YYYY h:mm A');
});
},
Please see the modified code below, i used moment js manipulation feature utcOffset so we can change the timezone of the clients date.
It will give us the corresponding server date/time based on the date/time on the client.
getServerTimeZone: function(newTime){
var _this = this;
$.ajax({
url: '/api/config/v1/system/time'
})
.done(function(data) {
if(!newTime){
newTime = new Date();
}
//Get Server Timezone and offset
//Offset is in milli sec. Converting it to hours
var serverTimeOffset = data.timeZoneOffset / (60 * 60 * 1000);
// Get current timezone offset for host device
var x = new Date();
var clientCurrentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
// change the timezone using utcOffset
serverTime = moment(x).utcOffset(serverTimeOffset).format('MM/DD/YYYY h:mm A');
});
},
You can test it here, i used -5 offset.
https://jsbin.com/puvutevomo/edit?html,js,output
If I'm understanding the requirement correctly you shouldn't need to send any timezone specific information up to the server. When a date/time is given in ISO8601 format (and has an x on the end) it is in UTC format. Timezones at that point are irrelevant and only used for display purposes.
moment will display that date/time in the user's correct timezone automatically (based on the browser settings).
var d = moment('2016-01-01T00:00:00.000Z');
console.log(d.format('llll')); //This will output the date/time relative to the user's timezone automatically
var sendToServer = d.toISOString() //send this string up to the server. It is in UTC format.
Good days guys. I have this nice and clean code for a running clock.
<script type="text/javascript">
function DisplayTime(){
if (!document.all && !document.getElementById)
return
timeElement=document.getElementById? document.getElementById("curTime"): document.all.tick2
var CurrentDate=new Date()
var hours=CurrentDate.getHours()
var minutes=CurrentDate.getMinutes()
var seconds=CurrentDate.getSeconds()
var DayNight="PM"
if (hours<12) DayNight="AM";
if (hours>12) hours=hours-12;
if (hours==0) hours=12;
if (minutes<=9) minutes="0"+minutes;
if (seconds<=9) seconds="0"+seconds;
var currentTime=hours+":"+minutes+":"+seconds+" "+DayNight;
timeElement.innerHTML="<font style='font-family:Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800&subset=latin,cyrillic-ext,latin-extfont-size:14px;color:#fff;'>"+currentTime+"</b>"
setTimeout("DisplayTime()",1000)
}
window.onload=DisplayTime
</script>
My only problem is it's based the system time. How can I set the timezone so that it will display the correct time based on the timezone specified?
There's nothing built into the JavaScript Date object that handles any timezones other than local (system) time and UTC.
You can do it by giving your Date instance the wrong time, using the delta between one of those timezones (local or UTC) and the time zone you want to use. It's easier if you use UTC.
So for instance, say we want our time in GMT+01:00:
var dt = new Date();
dt.setTime(dt.getTime() + (60 * 60 * 1000));
// ^^^^^^^^^^^^^^---- one hour in milliseconds,
// which is our offset from UTC/GMT
var hours = dt.getUTCHours(); // Use UTC methods to get time
var minutes = dt.getUTCMinutes();
var seconds = dt.getUTCSeconds();
Time stuff, particularly with timezones, is hard. You might look at using a library for it, although for just this sort of clock that would be overkill. One good library is MomentJS (which has a timezone add-on).
You can use getTimezoneOffset method of the Date object. It gives you the timezone offset, according to your timezone in minutes.
So in order to get the current time in UTC (+0 timezone) you can do something of the sort:
var tzOffset = CurrentDate.getTimezoneOffset();
// some timezones are not set hours, so we must calculate the minutes
var minutesOffset = parseInt(tzOffset%60,10);
// the offset hours for the timezone
var hoursOffset = parseInt(tzOffset/60, 10);
Then you need to do some math in your code to account for the offset:
var hours = CurrentDate.getHours() + hoursOffset;
var minutes = CurrentDate.getMinutes() + minutesOffset;
This would account for your timezone. If you want to calculate another timezone, that you specify, change the tzOffset above to show your timezone.
var tzOffset = CurrentDate.getTimezoneOffset() + TIMEZONE_HOURS*60;
TIMEZONE_HOURS is the timezone in hours you want, e.g. if you want UTC+3, you must set TIMEZONE_HOURS to 3.
As a whole timezones are a bit complicated task because they change a lot and there are some caveats with them. If you want to dwell more into this, check this answer in another question on SO
I have implemented your working code by adding one more function to obtain what you want. See this will help
function DisplayTime(timeZoneOffsetminutes){
if (!document.all && !document.getElementById)
return
timeElement=document.getElementById? document.getElementById("curTime"): document.all.tick2
var requiredDate=getTimeZoneTimeObj(timeZoneOffsetminutes)
var hours=requiredDate.h;
var minutes=requiredDate.m;
var seconds=requiredDate.s;
var DayNight="PM";
if (hours<12) DayNight="AM";
if (hours>12) hours=hours-12;
if (hours==0) hours=12;
if (minutes<=9) minutes="0"+minutes;
if (seconds<=9) seconds="0"+seconds;
var currentTime=hours+":"+minutes+":"+seconds+" "+DayNight;
timeElement.innerHTML="<font style='font-family:Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800&subset=latin,cyrillic-ext,latin-extfont-size:14px;color:#fff;'>"+currentTime+"</b>"
setTimeout("DisplayTime(-330)",1000)
}
window.onload=DisplayTime(-330);
function getTimeZoneTimeObj(timeZoneOffsetminutes){
var localdate = new Date()
var timeZoneDate = new Date(localdate.getTime() + ((localdate.getTimezoneOffset()- timeZoneOffsetminutes)*60*1000));
return {'h':timeZoneDate.getHours(),'m':timeZoneDate.getMinutes(),'s':timeZoneDate.getSeconds()};
}
#curTime{
background-color:#000;
}
<div id="curTime"></div>
visit this link as a reference
example:
var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
You can try using moment.js
It is very nice library which handles timezones too.