1

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

4
  • if you have Time and Date variables correct ... ${Date}T${Time}Z - you may want to add .000 before the Z though Commented Aug 10, 2021 at 13:50
  • It's good to learn how to manipulate dates by yourself. But dealing with dates is a complicated matter, and there are excellent libraries that will spare you the pain of reinventing the wheel. The most famous are Moment and its successor, Luxon Commented Aug 10, 2021 at 13:50
  • @JeremyThille Thank you sir, I was unaware of this before, I will try using Moment Thanks. Commented Aug 10, 2021 at 14:17
  • FYI - You probably shouldn't use MomentJS for new projects Commented Aug 10, 2021 at 15:46

1 Answer 1

3

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());

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the help but sir I am getting output as "Mon Aug 16 2021 07:15:00 GMT-0700 (Pacific Daylight Time)" not like " 2021-08-10T01:01:55.216Z" this is it because you passed date and time as string ?
I updated the answer for if your input is of a date type

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.