Convert timezone offset number of hours to timezone offset in (military?) hours - javascript

I am using WordPress and jQuery Timepicker.
Wordpress gives timezone offset in hours: like +2 or -3.5
jQuery Timepicker takes offset in military hours: +0200 or -0330
I am currently using something like this:
gmt_offset = -4;
hrs_offset = gmt_offset.replace('-', '-0') + "00";
= -0400
But that will break if the offset is not a single negative digit.
gmt_offset = -3.5;
hrs_offset = gmt_offset.replace('-', '-0') + "00";
= -03.500 //No good...
need: -0330
Ack! Can someone help me figure this out?

Split the offset into 2 parts using .split(".").
Give the hour part a "0" if it is less than 10. Then append a negative sign if it is originally negative.
var negative = hour < 0 ? true : false;
hour = Math.abs(hour) < 10 ? "0" + Math.abs(hour) : Math.abs(hour);
hour = negative ? "-" + hour : "+" + hour;
To calculate the minutes part, multiply it by 6.
(time[1]*6).toString()
Here's the final function:
function convertOffset(gmt_offset) {
var time = gmt_offset.toString().split(".");
var hour = parseInt(time[0]);
var negative = hour < 0 ? true : false;
hour = Math.abs(hour) < 10 ? "0" + Math.abs(hour) : Math.abs(hour);
hour = negative ? "-" + hour : "+" + hour;
return time[1] ? hour+(time[1]*6).toString() : hour + "00";
}
document.write(convertOffset(-3.5));
See DEMO.

function convert(gmt_offset) {
var sign ="+";
if(gmt_offset < 0) {
sign="-";
gmt_offset *= -1;
}
var hours = "0"+Math.floor(gmt_offset).toString();
var minutes = "0"+(Math.round(gmt_offset % 1 * 60)).toString();
return sign + hours.substr(hours.length - 2) + minutes.substr(minutes.length - 2);
}

Here's a nicely compact version:
function militaryGMTOffsetFromNumeric(offset) {
var dt = new Date(
Math.abs(offset) * 3600000 + new Date(2000, 0).getTime()
).toTimeString();
return (offset < 0 ? '-' : '+') + dt.substr(0,2) + dt.substr(3,2);
}
For example, militaryGMTOffsetFromNumeric(-3.5) returns -0330.

Related

Converting Excel Time to moment.js

I have an Electron app where an Excel-Sheet with a couple of columns containing time values needs to be imported. In my app those values are converted in a loop to momentjs object for further manipulation:
x['Time'] = moment(x['Time'], ['HH:mm','HH:mm:ss']).format('HH:mm:ss');
This works fine as long the Excel contains time values formatted as text. But if the Excel is set up the way it's meant to be, then the value of the Cell is a Number between 0 and 1 (Excel counts time internally as floating point - so e.g. 0,5 translates to 12:00:00).
Does anyone know how I can translate that back to a readable Timevalue for momentjs?
export const parseDateExcel = (excelTimestamp) => {
const secondsInDay = 24 * 60 * 60;
const excelEpoch = new Date(1899, 11, 31);
const excelEpochAsUnixTimestamp = excelEpoch.getTime();
const missingLeapYearDay = secondsInDay * 1000;
const delta = excelEpochAsUnixTimestamp - missingLeapYearDay;
const excelTimestampAsUnixTimestamp = excelTimestamp * secondsInDay * 1000;
const parsed = excelTimestampAsUnixTimestamp + delta;
return isNaN(parsed) ? null : parsed;
};
Usage:
new Date(parseDateExcel(36902.49097)) //=> Thu Jan 11 2001 11:46:59 GMT+0000 (Greenwich Mean Time)
Source
This is as far as I have work with the Excel time decimal values.
So according to Excel the time text is represented by a decimal number ranging from 0 to 1.
function excelDateToJSDate(excel_date, time = false) {
let day_time = excel_date % 1
let meridiem = "AMPM"
let hour = Math.floor(day_time * 24)
let minute = Math.floor(Math.abs(day_time * 24 * 60) % 60)
let second = Math.floor(Math.abs(day_time * 24 * 60 * 60) % 60)
hour >= 12 ? meridiem = meridiem.slice(2, 4) : meridiem = meridiem.slice(0, 2)
hour > 12 ? hour = hour - 12 : hour = hour
hour = hour < 10 ? "0" + hour : hour
minute = minute < 10 ? "0" + minute : minute
second = second < 10 ? "0" + second : second
let daytime = "" + hour + ":" + minute + ":" + second + " " + meridiem
return time ? daytime : (new Date(0, 0, excel_date, 0, -new Date(0).getTimezoneOffset(), 0)).toLocaleDateString(navigator.language, {}) + " " + daytime
};
First we define the midday, then handle the hours, minutes and seconds, then verify if the given hour is either AM or PM, as a formatting fashion preference we change the 24 hours to 12 hour convention and add padding zeros to any value less than 10 and lastly return the time or date as a string.
Example
function excelDateToJSDate(excel_date, time = false) {
let day_time = excel_date % 1
let meridiem = "AMPM"
let hour = Math.floor(day_time * 24)
let minute = Math.floor(Math.abs(day_time * 24 * 60) % 60)
let second = Math.floor(Math.abs(day_time * 24 * 60 * 60) % 60)
hour >= 12 ? meridiem = meridiem.slice(2, 4) : meridiem = meridiem.slice(0, 2)
hour > 12 ? hour = hour - 12 : hour = hour
hour = hour < 10 ? "0" + hour : hour
minute = minute < 10 ? "0" + minute : minute
second = second < 10 ? "0" + second : second
let daytime = "" + hour + ":" + minute + ":" + second + " " + meridiem
return time ? daytime : (new Date(0, 0, excel_date, 0, -new Date(0).getTimezoneOffset(), 0)).toLocaleDateString(navigator.language, {}) + " " + daytime
};
console.log(excelDateToJSDate(0.125, true));
console.log(excelDateToJSDate(43556));
Due to the fact I could not find a real answer, here is one that worked for me:
let fromExcel = 0,709722222222222; //translates to 17:02:00
let basenumber = (fromExcel*24)
let hour = Math.floor(basenumber).toString();
if (hour.length < 2) {
hour = '0'+hour;
}
var minute = Math.round((basenumber % 1)*60).toString();
if (minute.length < 2) {
minute = '0'+minute;
}
let Timestring = (hour+':'+minute+':00');
So I have a String momentjscan translate. The reason I do not mark this as answer is that there sure are nicer ways of conversion and I could not find a solution to calculate the seconds (which in my special case does not matter, as I do not use them).

Converting Float to Time in Javascript

I am having a three String or Float values say 9.30, 8.00 and 0.40 as Total_hour, Paid_hour, Extra_hour
These should be actually 9 hours 30 minutes, 8 hours 0 minutes, 0 hours 40 minutes.
Question 1) How to convert 9.30 to 9 hours 30 minutes
Question 2) Later want to Subtract and get Remaining Hour = Total_hour-Paid_Hour-Extra_hour
Later the answer Remaining Hour should be in float
This should work.
You just need to convert to ms:
let timefloat = 9.3;
function convertToMs(timefloat) {
// Get the minutes portion
let remainder = timefloat % 1;
// Convert into ms
let minutes = remainder * 100 * 60 * 1000;
// Get the number of hours and convert to ms
let hours = (timefloat - remainder) * 60 * 60 * 1000;
return minutes + hours;
}
// Convert back to float format
function convertToFloat(date) {
let hours = date.getUTCHours();
let mins = date.getUTCMinutes();
return hours + (mins / 100);
}
// Log the result
console.log(new Date(convertToMs(9.3)).toUTCString());
console.log(new Date(convertToMs(8.0)).toUTCString());
console.log(new Date(convertToMs(9.3) - convertToMs(8.0)).toUTCString());
let diff = convertToMs(9.3) - convertToMs(8.0);
console.log(convertToFloat(new Date(diff)))
The following javascript snippet converts a given float to hours and minutes. Source float to time
function convertNumToTime(number) {
// Check sign of given number
var sign = (number >= 0) ? 1 : -1;
// Set positive value of number of sign negative
number = number * sign;
// Separate the int from the decimal part
var hour = Math.floor(number);
var decpart = number - hour;
var min = 1 / 60;
// Round to nearest minute
decpart = min * Math.round(decpart / min);
var minute = Math.floor(decpart * 60) + '';
// Add padding if need
if (minute.length < 2) {
minute = '0' + minute;
}
// Add Sign in final result
sign = sign == 1 ? '' : '-';
// Concate hours and minutes
time = sign + hour + ':' + minute;
return time;
}
console.log(convertNumToTime(11.15));
Output
11:09
First convert the number in minutes and then do your subtraction. Then convert your output to hours.
var Total_hour = '9.30',
Paid_hour = '8.00',
Extra_hour = '0.40';
var conversionInMinutes = hour => Math.floor(hour) * 60 + (hour - (Math.floor(hour))) * 100;
var conversionInHours = min => Math.floor( min/60 ) + min % 60 / 100;
var Remaining_hour = conversionInMinutes(Total_hour) - conversionInMinutes(Paid_hour) - conversionInMinutes(Extra_hour);
console.log(conversionInHours(Remaining_hour).toFixed(2));
function doTime(input)
{
input = input.toString()
inputs = input.split(".")
return (inputs[0] + "Hour and" + inputs[1] + "minutes")
}
doTime("9:22")
function substract2
function subtract2(a , b){
a = input.toString()
arrayA = input.split(".")
b = input.toString()
arrayB = input.split(".")
h = parseInt(arrayB[0]) - parseInt(arrayA[0])
h <0 ? h+=12/*or 24*/ :h=h
m = parseInt(arrayB[1]) - parseInt(arrayA[1])
if(m<0){h-- ; m+=60}
return h.toString() + ":" + m.toString()
}

Removing Zero from Beginning of 24 Hour Time conversion

This is for a problem on Time Conversion from the 12-hour format to the military/24-hour time.
The standard input: 07:05:45PM
The expected output: 19:05:45
The standard/actual output: 019:05:45
The problem lies in the zero ^ at the beginning of the output.
I tried to set the parseInt() with a radix of 10 for the decimal numeral system but that didn't have any effect.
This is a result of this following code :
function main() {
var time = readLine();
var hours = parseInt(time.substr(0, 2), 10);
var minutes = parseInt(time.substr(3,5));
var seconds = parseInt(time.substr(6,8));
if ( time.indexOf('AM') !== -1 && hours === 12) {
time = time.replace('12', '00');
}
if (time.indexOf('PM') !== -1 && hours < 12) {
time = time.replace(hours, (hours + 12));
}
time = time.replace(/(AM|PM)/g, '');
console.log(time);
}
Any help would be appreciated!
You could just rebuild the string instead of using replace. Because you're using replace in your example you're just replacing the 7 with 19. Using replace will also cause issues if you have a time like 12:12:12.
ex.
function main() {
var time = readLine();
var hours = parseInt(time.substr(0, 2), 10);
var minutes = time.substr(3,5);
var seconds = time.substr(6,8);
if ( time.indexOf('AM') !== -1 && hours === 12) {
hours = 0;
}
else if (time.indexOf('PM') !== -1 && hours < 12) {
hours += 12;
}
time = (hours < 10 ? "0" + hours : hours) + ':' + minutes + ':' + seconds;
console.log(time);
}

Time conversion from 24hrs to 12hrs

I am getting the time like 13.40, but i need to convert it to 1.40.. any one know, what is the best way to do this. i am using jquery to make time.
my code is :
var time = new Date(myDate);
var hours = time.getHours();
alert(hours);
if (hours > 12) {
hours -= 12;
}
Um, as simple as that.
Use the modulus operator, % for this
var input = "13.40";
var atoms = input.split(".");
var output = atoms[0] % 12 + "." + atoms[1];
output; // "1.40";
If you want to prefix with 0 then you can do this
var output = ("0" + atoms[0] % 12).slice(-2) + "." + atoms[1];
output; // "01.40";
If you want AM/PM as a suffix
var output = ("0" + atoms[0] % 12).slice(-2) + "." + atoms[1] +
(atoms[0] < 13 ? " AM" : " PM");
output; // "01.40 PM";
Try
hours = hours > 12 ? hours - 12 : hours;
You can use the modulo operator for this:
var hours = time.getHours() % 12

Javascript: How to turn the time (stored as a fraction) into a readable string?

I have the time stored as a fraction (done so it can be displayed on a graph), e.g. 15.5 is 3.30pm and 23.25 is 11.15pm. I need to turn those numbers into strings in the format HH:MM:SS. Is there a simple way of doing this?
var fraction = 23.5;
var date = new Date(2000, 1, 1); // use any date as base reference
date.setUTCSeconds(fraction * 3600); // add number of seconds in fractional hours
Then use a date formatting script such as this, or Date.js if you're not fond or formatting and padding.
date.format("HH:MM:ss"); // 23:30:00
See an example. I'm using the formatting function from here.
Something like this ?
var fraction = 14.5;
var hours = Math.floor(fraction); // extract the hours (in 24 hour format)
var mins = 60 * (fraction - hours); // calculate the minutes
t = new Date(); // create a date/time object
t.setHours(hours); // set the hours
t.setMinutes(mins); // set the mins
console.log(t.toTimeString()); //show it
or completely manual
var fraction = 14.5;
var hours = Math.floor(fraction);
var mins = 60 * (fraction - hours);
var ampm = ((fraction % 24) < 12) ? 'am' : 'pm';
formatted = ('0' + hours % 12).substr(-2) + ':' + ('0' + mins).substr(-2) + ':00 ' + ampm;
console.log(formatted);
Update
And a version with seconds as well..
var fraction = 14.33;
var hours = Math.floor(fraction);
var allseconds = 3600 * (fraction - hours);
var minutes = Math.floor(allseconds / 60);
var seconds = Math.floor(allseconds % 60);
var ampm = ((fraction % 24) < 12) ? 'am' : 'pm';
formatted = ('0' + hours % 12).substr(-2) + ':' + ('0' + minutes).substr(-2) + ':' + ('0' + seconds).substr(-2) + ' ' + ampm;
console.log(formatted);
Manual function:
var time = function(num) {
if(num < 0 || num >= 24) {throw "Invalid number");}
var x = num > 13 ? num - 12 : num;
var h = Math.floor(x);
var min = x - h;
var ampm = num >= 12 && num < 24 ? "pm" : "am";
return (h + ":" + Math.floor(min * 60) + ampm);
};
Tests:
time(13.40); // 1:24pm
time(11.25); // 11:15pm
time(12.50); // 12:30pm
time(23.50); // 11:30pm
time(0.50); // 0:30am
time(24.00); // error!!

Categories

Resources