1

I have two variables here (datetime and time)

And I want to add the time to the datetime variable.

var datetime = '2020/09/21 09:33:00';
var time = '00:00:23';
var result = datetime + time; // I know this is wrong

How can I add the two variables so that the result will be

2020/09/21 09:33:23
JSN
  • 1,281
  • 3
  • 22
  • 48
  • I think you have misread the data. Your datetime should be in the format yyyy/mm/dd hh:mm:ss. So did you actually want ```2020/09.21 9:33:23``` as your output? Or am I misunderstanding something? – The Grand J Sep 21 '20 at 02:19
  • `00:00:23` is what? ??:HH:MM ?? – epascarello Sep 21 '20 at 02:20
  • 1
    that should be actually `var datetime = '2020/09/21 00:09:33';` – JSN Sep 21 '20 at 02:20
  • You are defining strings, so the `+` will just concatenate. You need the `Date` object. See @Derek.W solution below – GetSet Sep 21 '20 at 02:22
  • 2
    Does this answer your question? [How to add 30 minutes to a JavaScript Date object?](https://stackoverflow.com/questions/1197928/how-to-add-30-minutes-to-a-javascript-date-object) – The Grand J Sep 21 '20 at 02:22
  • sorry I was wrong, that should be `var datetime = '2020/09/21 09:33:00';` – JSN Sep 21 '20 at 02:54

2 Answers2

2
var date = new Date('2020/09/21 9:33');
var time = 23 * 1000;  // in miliseconds
var result = new Date(date.getTime() + time);
Derek Wang
  • 9,720
  • 4
  • 15
  • 38
0

So you need to calculate number of seconds and add it to the date

const datetime = '2020/09/21 00:09:33';
const time = '00:00:23';
const parts = time.split(":");
const seconds = +parts[0] * 3600 + +parts[1] * 60 + +parts[2];
const date = new Date(datetime);
date.setSeconds(date.getSeconds() + seconds);

console.log(date.toLocaleString())
epascarello
  • 195,511
  • 20
  • 184
  • 225