-2

I am currently having a list of time string

1: 20:15
2: 20:15
3: 20:15
4: 19:15
5: 20:00
6: 19:15
7: 20:15
8: 20:15
9: 19:00
10: 19:15
11: 20:15
12: 19:00
13: 20:00
14: 20:00 
15: 20:00
16: 20:00

since they are not in my local timezone I would like to add 2 hours to every time on the list but I am not sure how to do this with the Date function since I only have access to the hours and minutes rather than the full date.

This might be something simple but to be honest this is my first time using dates in JS.

The Output should look like

1: 22:15
2: 22:15
3: 22:15
4: 21:15
5: 22:00
6: 21:15
7: 22:15
8: 22:15
9: 21:00
10: 21:15
11: 22:15
12: 21:00
13: 22:00
14: 22:00 
15: 22:00
16: 22:00

I am getting the string from an API so this also has to work for any other list of strings (Format: HH:mm).

Since this is one of my learning projects I would rather enjoy implementing this without an external script.

Ironlors
  • 173
  • 3
  • 19
  • 3
    When working with dates/time/timezones I *highly* recommend using [momentjs](https://momentjs.com), which supports things like `moment('20:15', 'hh:mm').add(2, 'hours')`. – Jeffrey Roosendaal Jul 26 '18 at 14:48
  • This question may help, also using mommentjs: https://stackoverflow.com/questions/10087819/convert-date-to-another-timezone-in-javascript – Alex Boyle Jul 26 '18 at 14:51
  • Sorry for not saying this in the question. This is for one of my learning projects so I would rather enjoy implementing this without any external scripts or libraries. – Ironlors Jul 26 '18 at 14:56
  • @JeffreyRoosendaal momentjs is a over the top for this simple problem – phuzi Jul 26 '18 at 14:56

2 Answers2

4

You should probably split each time in to hours and minutes, parseInt the hours, add 2 and the recombine

let times = ["20:15", "20:15", "20:15", "19:15", "20:00", "19:15", "20:15", "20:15", "19:00", "19:15", "20:15", "19:00", "20:00", "20:00", "20:00", "20:00"];

let updatedTimes = times.map(time => {
  let [hours, minutes] = time.split(':');

  // add 2 hours, make sure it's not more than 23
  hours = (parseInt(hours) + 2) % 24;

  return [hours, minutes].join(':');
});

console.log(updatedTimes);
phuzi
  • 12,078
  • 3
  • 26
  • 50
1

For this use case, it's probably simpler to just split the string and update it that way.

var times = [
"20:15",
"20:15",
"20:15",
"19:15",
"20:00",
"19:15",
"20:15",
"20:15",
"19:00",
"19:15",
"20:15",
"19:00",
"20:00",
"20:00",
"23:00",
"20:00"
]

function add2hours(time){
  let HM = time.split(':'),
    h = parseInt(HM[0]) + 2, m = HM[1]
    
  if(h > 23) h -= 24
    
  return [h, m].join(':')
  
}

console.log(times.map(add2hours))
jmcgriz
  • 2,819
  • 1
  • 9
  • 11