1

I have my string which contains time like var time = '11:50 AM'

I try to add 10 minutes to my string, so it should be like 12:00 PM, the both minutes and (AM/PM) has to be changed.

How to perform this kind of operations? In JavaScript.

as I'm new to the technology, please help me out.

jansha
  • 164
  • 1
  • 8
  • Wouldn't this be easier if you used actual time values? String manipulation only gets you so far. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date – isherwood Jan 17 '22 at 17:15
  • Does this help? [convert time string to time value in javascript](https://stackoverflow.com/questions/46591254/converting-a-time-string-to-a-time-value-in-javascript) – freedomn-m Jan 17 '22 at 17:20
  • Start with this: [*Add 20 minutes in string time and populate it in the textbox or alert it*](https://stackoverflow.com/questions/13338960/add-20-minutes-in-string-time-and-populate-it-in-the-textbox-or-alert-it), then convert from HH:mm to h:mm a/p: [*Converting 24 hour time to 12 hour time w/ AM & PM using Javascript*](https://stackoverflow.com/questions/4898574/converting-24-hour-time-to-12-hour-time-w-am-pm-using-javascript?r=SearchResults&s=1|383.7274). – RobG Jan 18 '22 at 02:48

1 Answers1

-2

Here's one way to do it in a few easy to read steps.

However, working with dates in vanilla JavaScript can be tricky. It might be worth looking into a library like Moment.js which makes working with dates/times easier.

// string
var timeString = '11:50';
// create proper date with the string
var date = new Date('2022-01-01T' + timeString+ ':00Z');
// add 10 minutes
var newDate = new Date(date.getTime() + 10*60000);
// split the new string
var newDateSplit = newDate.toTimeString().split(':');
// get hour and minutes from split date
var newTimeString = newDateSplit[0] + ':' + newDateSplit[1];

console.log('original time: ' + timeString)
console.log('new time: ' + newTimeString)
Ryan Walls
  • 191
  • 1
  • 13