I want to convert a 12-hour format time into a string, add some minutes, then convert back to string. My user will be entering a time as a sting example 8:03 AM this time needs to converted into an integer with 9 minutes added to it then converted back to the same 12-hour format just 9 minutes into the future.
I've tried to make a Date obj using the string time, but when I do the Date constructor says I am using an invalid date.
new Date("8:03 AM")
What I tried after that was adding a speicifc date to the time
new Date("09/10/2022 8:03 AM")
That worked to create a Date obj and then I would try to get just the time using .getTime() and pass that into my intToHHMM function.
const intToHHMM = function (time) {
var sec_num = parseInt(time, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0" hours;}
if (minutes < 10) {minutes = "0" minutes;}
if (seconds < 10) {seconds = "0" seconds;}
return hours ':' minutes;
}
But I am getting a weird return that definitely is not hh:mm format.
Can someone lend a hand, I appreciate the help in advance!
CodePudding user response:
Just check this out.
var date = new Date("09/10/2022 8:03 AM");
var options = {
hour: 'numeric',
minute: 'numeric',
hour12: true
};
var timeString = date.toLocaleString('en-US', options);
console.log(timeString);
function addMinutes(date, minutes) {
return new Date(date.getTime() minutes*60000);
}
var timePlusNineMinString=addMinutes(date,9).toLocaleString('en-US', options);
console.log(timePlusNineMinString);
CodePudding user response:
check this function, pass any time and it will add minsToAdd
minutes to start
. Correct any mistakes when see them.
function addMins(start, minsToAdd) {
let am_pm = start.split(" ")[1]
let [hr, min] = start.split(" ")[0].split(":")
let future = ""
min = parseInt(min) minsToAdd
if (min > 59) {
min = min - 60
hr = parseInt(hr) 1
am_pm = hr > 11 ?
am_pm === "PM" ? "AM" : "PM" :
am_pm === "AM" ? "PM" : "AM";
hr = hr > 12 ? hr - 12 : hr;
future = [
`${parseInt(hr)}`.length === 1 ? `0${hr}` : `${hr}`,
`${min}`.length === 1 ? `0${min}` : `${min}`,
am_pm
].join(":")
} else {
future = [`${hr}`.length === 1 ? `0${hr}` : `${hr}`,
`${min}`.length === 1 ? `0${min}` : `${min}`,
am_pm
].join(":")
}
return future
}
console.log(addMins("11:56 AM", 9)) //12:05:PM
console.log(addMins("11:56 PM", 9)) //12:05:AM
console.log(addMins("19:03 PM", 9)) //19:12:PM
CodePudding user response:
Generally I can say, you can use momentjs. but if you can share the part of your code there might be better and more accurate solutions.