Removing Zero from Beginning of 24 Hour Time conversion - javascript

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

Related

Changing a function to also work for negative values?

I have a function inside my app that takes a value and puts it out in a special way. It is there to calculate a value to be the same value but split in "hours : minutes".
I need the function to also work for negative values - something like an if check inside the function to check if the entered time is negative and then to change the calculation/output.
Here is the function its pretty straight forward:
const calcSingle = time => {
// insert a if check somewhere here to check for time and if its negative
let hour = Math.floor(time / 60);
let minutes = time % 60;
hour = hour < 10 ? "0" + hour : hour;
minutes = minutes < 10 ? "0" + minutes : minutes;
return hour + ":" + minutes;
};
If I call this on for example:
calcSingle(200) I get back "03:20" which is the correct value.
However if I try calcSingle(-200) I get: "0-4:0-20" which obviously is wrong because it should be the same value but with a minus so this => "-03:20".
const calcSingle = time => {
// insert a if check somewhere here to check for time and if its negative
let hour = Math.floor(time / 60);
let minutes = time % 60;
hour = hour < 10 ? "0" + hour : hour;
minutes = minutes < 10 ? "0" + minutes : minutes;
return hour + ":" + minutes;
};
console.log(
calcSingle(200)
)
console.log(
calcSingle(-200)
)
Edit: Thanks for all the responses from all of you guys I will use math.abs it solves my problem! Great help guys - have a good day!
You can add check at beginning and call same function changing sign.
if (time < 0) {
return `-${calcSingle(Math.abs(time))}`;
}
Like this
const calcSingle = time => {
if (time < 0) {
return `-${calcSingle(Math.abs(time))}`;
}
// insert a if check somewhere here to check for time and if its negative
let hour = Math.floor(time / 60);
let minutes = time % 60;
hour = hour < 10 ? "0" + hour : hour;
minutes = minutes < 10 ? "0" + minutes : minutes;
return hour + ":" + minutes;
};
console.log(calcSingle(200));
console.log(calcSingle(-200));
I think a Math.abs() will solve your problem:
const calcSingle = time => {
let isNegative = time < 0;
let _time = Math.abs(time);
// insert a if check somewhere here to check for time and if its negative
let hour = Math.floor(_time / 60);
let minutes = _time % 60;
hour = hour < 10 ? "0" + hour : hour;
minutes = minutes < 10 ? "0" + minutes : minutes;
return (isNegative ? '-':'') + hour + ":" + minutes;
};
console.log(
calcSingle(200)
)
console.log(
calcSingle(-200)
)
Simplest version
const pad = num => ("0" + num).slice(-2);
const calcSingle = time => {
let _time = Math.abs(time);
let hour = pad(Math.floor(_time / 60));
let minutes = pad(_time % 60);
return (time < 0 ? '-' : '') + hour + ":" + minutes;
};
console.log(
calcSingle(200)
)
console.log(
calcSingle(-200)
)
Math.abs can be used.
Math.abs()
const calcSingle = time => {
// insert a if check somewhere here to check for time and if its negative
let _time = Math.abs(time);
let hour = Math.floor(_time / 60);
let minutes = _time % 60;
hour = hour < 10 ? "0" + hour : hour;
minutes = minutes < 10 ? "0" + minutes : minutes;
return (time < 0 ? '-' : '') + hour + ":" + minutes;
};
console.log(calcSingle(200), calcSingle(-200));
You could use Math.abs() to get the absolute value of time. You can then check in your return statement whether your initial time is less than 0 (therefore a negative number) and use that to return either a positive or negative time.
You could use the following code:
const calcSingle = time => {
const absTime = Math.abs(time);
let hour = Math.floor(absTime / 60);
let minutes = absTime % 60;
hour = hour < 10 ? "0" + hour : hour;
minutes = minutes < 10 ? "0" + minutes : minutes;
return `${time < 0 ? "-" : ""}${hour}:${minutes}`;
};
Use a boolean to store the value and append the minus at the end of result
calcSingle = time => {
var bIsNegative = false;
if (time < 0) {
bIsNegative = true;
}
time = Math.abs(time);
// insert a if check somewhere here to check for time and if its negative
let hour = Math.floor(time / 60);
let minutes = time % 60;
hour = hour < 10 ? "0" + hour : hour;
minutes = minutes < 10 ? "0" + minutes : minutes;
return bIsNegative ? "-" + (hour + ":" + minutes) : hour + ":" + minutes;
};
console.log(
calcSingle(200)
)
console.log(
calcSingle(-200)
)

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

Check if time is between two values with hours and minutes in javascript

I need to check if a time is between a start and end time. All times are on the same day, so date is not important. I'm able to compare hours, but I'm unsure how to add in minutes to the start and end times.
var thedate = new Date();
var dayofweek = thedate.getUTCDay();
var hourofday = thedate.getUTCHours();
var minutesofday = date.getMinutes();
function inTime() { if (dayofweek != 0 && dayofweek != 7 && (hourofday > 13 && hourofday < 20)) { return true; } return false; }
If I want to check whether the time is between 13:05 and 19:57, how would I add the minutes to my inTime function? If I add them to the if statement, it fails to work:
function inTime() { if (dayofweek != 0 && dayofweek != 7 && ((hourofday > 13 && minutesofday > 5) && (hourofday < 20 && minutesofday < 57))) { return true; } return false; }
If its 14:04 your condition will fail as 4 is smaller 5. The simplest would probably be to just take the full minutes of the day:
const start = 13 * 60 + 5;
const end = 19 * 60 + 57;
const date = new Date();
const now = date.getHours() * 60 + date.getMinutes();
if(start <= now && now <= end)
alert("in time");
If you're saying you want to check if the time "now" is between two times, you can express those times as minutes-since-midnight (hours * 60 + minutes), and the check is quite straightforward.
For instance, is it between 8:30 a.m. (inclusive) and 5:00 p.m. (exclusive):
var start = 8 * 60 + 30;
var end = 17 * 60 + 0;
function inTime() {
var now = new Date();
var time = now.getHours() * 60 + now.getMinutes();
return time >= start && time < end;
}
console.log(inTime());
The above uses local time; if you want to check UTC instead, just use the equivalent UTC methods.
Convert times to milliseconds and then you can compare easily.
short version:
if(timeToCheck.getTime() >= startTime.getTime() &&
timeToCheck.getTime() <= endTime.getTime()) {
// ...
}
OR:
let startTimeMilli = startTime.getTime();
let endTimeMilli = endTime.getTime();
let timeToCheckMilli = timeToCheck.getTime();
// change >= to > or <= to < as you need
if (timeToCheckMilli >= startTimeMilli && timeToCheckMilli <= endTimeMilli) {
// do your things
}

How to work out time difference between two times on a 24 hour clock

I have a problem with some code I have been producing in JavaScript. I want to calculate the difference between two times on a 24 hour clock. The data comes from two input time fields:
<input type="time" id="start" />
<input type="time" id="end" />
Because of this the times come in a string 00:00, which doesn't help for number calculations.
The way I worked it out was to minus the start from the end. This works perfectly if the the end time is greater, however if the end time is past 11:00 (00:00), I end up with a negative number. I have tried adding 24 to the result if the end is lower than the start but I still get a negative number. This may seem like a dumb question but I was never that good at maths.
var numHours;
if(time_end < time_start){
numHours = parseInt(t_e.substring(0,2)) - parseInt(t_s.substring(0,2)) + 24;
}else{
numHours = parseInt(t_e.substring(0,2)) - parseInt(t_s.substring(0,2));
}
There is probably (definitely) a better way of doing this but how can I get this to work. Also could I calculate the minutes as well to get more accurate time difference.
The solutions provided aren't accounting for the day boundary effectively. And all of this assumes the difference is less than 24 hours. Meaning that we have an upper boundary on the difference between start and end of 23 hours and 59 minutes, otherwise we are confused by the result. But remember that as described a real use case is that an event starts at 11pm and ends at 1am (from 23:00 to 1:00) and the difference is 2 hours NOT 22 hours.
function calculateTime(e) {
var startTime = $('#start').val();
var endTime = $('#end').val();
var startTimeArray = startTime.split(":");
var startInputHrs = parseInt(startTimeArray[0]);
var startInputMins = parseInt(startTimeArray[1]);
var endTimeArray = endTime.split(":");
var endInputHrs = parseInt(endTimeArray[0]);
var endInputMins = parseInt(endTimeArray[1]);
var startMin = startInputHrs*60 + startInputMins;
var endMin = endInputHrs*60 + endInputMins;
var result;
if (endMin < startMin) {
var minutesPerDay = 24*60;
result = minutesPerDay - startMin; // Minutes till midnight
result += endMin; // Minutes in the next day
} else {
result = endMin - startMin;
}
var minutesElapsed = result % 60;
var hoursElapsed = (result - minutesElapsed) / 60;
alert ( "Elapsed Time : " + hoursElapsed + ":" + (minutesElapsed < 10 ?
'0'+minutesElapsed : minutesElapsed) ) ;
}
And I didn't check, but I believe you could just do this, but I'm not checking it :
var result = endMin - startMin;
if (result < 0 ) result = (24*60) + result;
A simple solution that might work best for this limited use-case is to convert both times into total minutes since the start of the day, and then subtract.
Pseudocode:
startMin = startInputHrs * 60 + startInputMin
endMin = endInputHrs * 60 + endInputMin
timeDifference = endMin - startMin
It's up to you how you want to handle a negative result. Maybe give the user an error message, and tell them that the start time has to come before the end time?
I'm a beginner, and some whiz is probably going to come up with an answer in like 2 lines :), but here it is.....this works. input is a string in the form of "1:20pm-2:30am".
function CountingMinutesI(str) {
split = str.split('-')
startTime = split[0]
endTime = split[1]
// for end time
if (endTime === '12:00am') { endInMinutes = 0}
else if (endTime.charAt(endTime.length-2) === 'a') {
if (endTime.substr(0, 2) === '12') {
endInMinutes = parseInt(endTime.split(':')[1].replace(/[a-z]/gi, ''))
}
else {
endHours = endTime.split(':')[0]
endMins = endTime.split(':')[1].replace(/[a-z]/gi, '')
endInMinutes = (parseInt(endHours)*60) + parseInt(endMins)
}
}
else if (endTime === '12:00pm') {endInMinutes = 720}
else {
endHours = endTime.split(':')[0]
endMins = endTime.split(':')[1].replace(/[a-z]/gi, '')
endInMinutes = (parseInt(endHours)*60 + 720) + parseInt(endMins)
}
// for start time
if (startTime === '12:00am') { startInMinutes = 0}
else if (startTime.charAt(startTime.length-2) === 'a') {
if (startTime.substr(0, 2) === '12') {
startInMinutes = parseInt(startTime.split(':')[1].replace(/[a-z]/gi, ''))
}
else {
startHours = startTime.split(':')[0]
startMins = startTime.split(':')[1].replace(/[a-z]/gi, '')
startInMinutes = (parseInt(startHours)*60) + parseInt(startMins)
}
}
else if (startTime.substr(0,2) === '12') {startInMinutes = 720 + parseInt(startTime.split(':')[1].replace(/[a-z]/gi, ''))}
else {
startHours = startTime.split(':')[0]
startMins = startTime.split(':')[1].replace(/[a-z]/gi, '')
startInMinutes = (parseInt(startHours)*60 + 720) + parseInt(startMins)
}
if (endInMinutes > startInMinutes) {output = endInMinutes - startInMinutes}
else {output = 1440 - (startInMinutes - endInMinutes)}
return output
}

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

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.

Categories

Resources