Amara
Amara

Reputation: 351

How to merge Date and Time using Javascript

I am new to JavaScript and don't know much. I know there are already many similar questions available but I didn't get what I was looking for. I am having 2 inputs one is datePicker and other one is timePicker.

<form>
<div class="form-group">
<label for="a">Date :</label>
<input class="form-control" ng-model="res.Date" ng-required="true" type="date" >
</div>
<div class="form-group">
<label for="a">Time :</label>
<input class="form-control timepicker" ng-model="res.Time" ng-required="true" 
type="time">
</div>
</form>

I am getting date and time separately and in different format - I have converted the date in yyyy/mm/dd format and also formatted the time using the below code -

 var timeString = $scope.res.Time.getHours() + ':' + $scope.res.Time.getMinutes() + ':00';
 var d = new Date($scope.res.Date),
 month = '' + (d.getMonth() + 1),
 day = '' + d.getDate(),
 year = d.getFullYear();
 if (month.length < 2)
 month = '0' + month;
 if (day.length < 2)
 day = '0' + day;
 var fdate = [year, month, day].join('-')

I am getting date and time like -

Time = 20:42:00
Date = 2021-08-11

But now I want to join them and want to make it like this = 2021-08-10T01:01:55.216Z

I tried few things like parsing but that didn't given me this format. Sorry for the mistakes. Please Help me in getting this. Thank you

Upvotes: 1

Views: 514

Answers (1)

Reda Benchraa
Reda Benchraa

Reputation: 289

let time = "20:42:00";
let date = new Date("2021-08-11");

let parsedDate = new Date(Date.parse(date.toDateString() + ' ' + time));

console.log(parsedDate.toISOString());

Upvotes: 3

Related Questions