converting getTimezoneOffset() into static timezone - javascript

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

Related

Getting a negative number when calculating time in javascript

I'm working on a pdf form and trying to calculate hours from 2 fields. As long as the time does not go past midnight (in 24-hour format), I get the correct response. Once it goes past midnight, I get a negative number. Is there a way to add 24 hours to the returned value if it gives a negative number?
Here's what the field is being calculated as
var startTime = this.getField("SHIFT STARTRow1").value;
var endTime = this.getField("SHIFT ENDRow1").value;
this.getField("TOTAL HOURSRow1").value = timeDiff(startTime, endTime);
if ((event.value == "") || (event.value == Infinity) || isNaN(event.value)) {event.value = "";}
And here is the form javascript - timeDiff
function timeDiff(startTime, endTime) {
var startArr = startTime.split(":");
var endArr = endTime.split(":");
var startDate = new Date(0, 0, 0, startArr[0], startArr[1], 0);
var endDate = new Date(0, 0, 0, endArr[0], endArr[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = diff / 1000 / 60 / 60;
return hours.toFixed(2)
}
console.log(timeDiff('6:24', '8:13')) // 1.82
So using this script, if I type in 12:30 as the start time and 01:45 as the end time, I get a return of -10.75. However, I need a return of 13.25.
I attempted to find another thread that helped me with this, but maybe I overlooked it. Any help?
Example
If end hour is less than start, add 24
function timeDiff(startTime, endTime) {
var startArr = startTime.split(":").map(Number);
var endArr = endTime.split(":").map(Number);
if (startArr[0] > endArr[0]) {
endArr[0] += 24;
}
var hours = endArr[0] + endArr[1]/60 - startArr[0] - startArr[1]/60;
return hours.toFixed(2)
}
console.log(timeDiff('23:10', '1:00'))
Is there a way to add 24 hours to the returned value if it gives a negative number?
Well, yes –
if(hours < 0) hours += 24;

Javascript - different timestamp values on the same client

Can someone please explain why these 3 different lines that suppose to produce the exact same result, give three different results?
The only accurate one is the 2'nd line (Date.now()). Unfortunately, this is the only one I can't use.
function show_ts_date(idx, ts)
{
var a = new Date(ts * 1000);
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes();
var sec = a.getSeconds();
var formattedTime = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;
alert(idx+'. timestamp: '+ts+' Date: '+formattedTime);
}
var currentdate = new Date();
//line 1: (produces wrong timestamp - it gives the wrong hour (-4) when I convert back to dateTime)
timestamp_1 = Math.floor(new Date(currentdate.getFullYear()+'-'+(currentdate.getMonth()+1)+'-'+currentdate.getDate()+'T'+currentdate.getHours()+':'+currentdate.getMinutes()+':00') / 1000);
show_ts_date(1, timestamp_1);
//line 2 (produces correct timastamp - it gives the correct hour when I convert back to DateTime.)
timestamp_2 = Math.floor(Date.now() / 1000);
show_ts_date(2, timestamp_2);
//line 3 (produces wrong timestamp - it gives the wrong hour (+3) when I convert back to dateTime)
let dat = new Date(Date.UTC(currentdate.getFullYear(), currentdate.getMonth(), currentdate.getDate(), currentdate.getHours(), currentdate.getMinutes(), 00));
timestamp_4 = Math.floor( dat/ 1000);
show_ts_date(4, timestamp_4);
Well, assuming that Date.now() returns the real accurate value (I doubt it is always the case, But that's what I'm left with. you can always convert it back to Date and check if the right date & time came back),
I wrote this function that will compare between the right and wrong timestamps and will add (or decrease) the number of milliseconds from (or to) the false timestamp - turning it in to a correct one:
function getTimestampMilisecondsGap()
{
var currentdate = new Date();
timestamp_1 = Math.floor(new Date(currentdate.getFullYear()+'-'+(currentdate.getMonth()+1)+'-'+currentdate.getDate()+'T'+currentdate.getHours()+':'+currentdate.getMinutes()+':00') / 1000);
//let dat = new Date(Date.UTC(currentdate.getFullYear(), currentdate.getMonth(), currentdate.getDate(), currentdate.getHours(), currentdate.getMinutes(), 00));
//timestamp_1 = Math.floor( dat/ 1000);
timestamp_2 = Math.floor(Date.now() / 1000); //this one is suppose to produce a correct timestamp
var addTimeStampMilisecs = 0;
if (timestamp_2 > timestamp_1)
{
addTimeStampMilisecs = timestamp_2-timestamp_1;
}
else if (timestamp_2 < timestamp_1)
{
addTimeStampMilisecs = timestamp_1-timestamp_2;
}
return addTimeStampMilisecs;
}
//writing a timestamp to the database
var destinationDateTimeStr = document.getElementById("dateyear").value+"-"+document.getElementById("datemonth").value+"-"+document.getElementById("dateday").value+"T"+document.getElementById("datehour").value+":"+document.getElementById("dateminute").value+":00";
var date2 = new Date(destinationDateTimeStr);
var eventDateTS = Math.floor(date2 / 1000); //convert to timestamp (with incorrect timezone)
eventDateTS += getTimestampMilisecondsGap(); //add (or decrese) the number of miliseconds from the timestamp because this function that generates the tmestamp returns a wrong number (the hour in the converted date is wrong)
//write the correct eventDateTS to your DB here...

How to convert GMT time to Local time?

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

JavaScript: Parse time string and add minutes to it

$.getJSON("api/times", function(times) {
var time1 = times.departure; // 14:36:30 (string)
var minutesToAdd = parseInt(times.minutesToAdd); // 6
var total = "?"; // How can I add minutesToAdd to time1?
});
I am trying to parse time1 so that I can add the minutesToAdd value to the time. The time1 value comes directly from a MySQL database. It is obtained through an API that returns this data in JSON. How can I do this?
I think you can try this
on line 1 : You have to add a demo date with the time in javascript so that you can create the date object. Later you can do date.getTime() to get the time in milisecond.
var newDateObj = new Date("01/01/13 14:36:30"); // '01/01/13' is the demo value
alert(newDateObj)
var date = new Date(newDateObj.getTime() + 5*60000);
alert(date) // date.getTime() will give you the time
I you don't want to use Date, use split to get the three parts of your time string. Then you just add your minutes and make sure you don't exceed 59 minutes (if you think it is useful, check if hours doesn't exceed 23) :
$.getJSON("api/times", function(times) {
var time1 = times.departure; // 14:36:30 (string)
var minutesToAdd = parseInt(times.minutesToAdd);
var time = time1.split(':');
var time[1] += minutesToAdd;
if (time[1] >= 60) {
time[1] = 0;
time[0]++; // maybe you should test if >= 24
}
var total = time.join(':'); // equivalent to "time[0]+':'+time[1]+':'+time[2]"
});`

jQuery-validating start time and end time selected using time picker

I want to validate start time and end time selected using timepicker which is in 12 hr format. The end time should be greater than the start time. I used an if statement but when the test is using values such as 8:00 AM as start time and 1:00 PM as end time, it is not working. What can I do to solve this problem. Someone please help me with this. I am stuck with this since yesterday. I want just time ,i don't need date.
$("#dateTimeAddButton").click(function ()
{
var Date=$('#myDatePickerId').val()
var startTime = $('#i').val();
var endTime = $('#i1').val();
if (startTime > endTime)
{
alert('End time always greater then start time.');
}
});
First convert to lowest denominational (minute here). Then compare it.
st = minFromMidnight(startTime);
et = minFromMidnight(endTime);
if(st>et){
alert("End time must be greater than start time");
}
function minFromMidnight(tm){
var ampm= tm.substr(-2)
var clk = tm.substr(0, 5);
var m = parseInt(clk.match(/\d+$/)[0], 10);
var h = parseInt(clk.match(/^\d+/)[0], 10);
h += (ampm.match(/pm/i))? 12: 0;
return h*60+m;
}
please try that below code in case you have length of time more than 6 char like 10:00am instead of 9:00am will throw error above code.
I did minor changes in above code and it worked like charm for me.
$('#btnSubmit').on('click', function () {
var startTime = $('#txtJobStartTime').val();
var endTime = $('#txtJobEndTime').val();
var st = minFromMidnight(startTime);
var et = minFromMidnight(endTime);
if (st > et) {
alert('End time always greater then start time.');
return false;
}
function minFromMidnight(tm) {
var ampm = tm.substr(-2);
var clk;
if (tm.length <= 6) {
clk = tm.substr(0, 4);
} else {
clk = tm.substr(0, 5);
}
var m = parseInt(clk.match(/\d+$/)[0], 10);
var h = parseInt(clk.match(/^\d+/)[0], 10);
h += (ampm.match(/pm/i)) ? 12 : 0;
return h * 60 + m;
}
});

Categories