Jahongir Rahmonov
Jahongir Rahmonov

Reputation: 13723

how to get whole Date object from input date and input time in javascript

I have these two inputs:

<input type="date" ng-model="year">
<input type="time" ng-model="time">

I want to create a Date object from these two values. Something like this:

new Date(year, time);

how can I do that?

Upvotes: 1

Views: 624

Answers (2)

Alexis King
Alexis King

Reputation: 43842

You can manually add the two dates together in your controller. If you want this to automatically update on your controller scope, then you can use a watch expression in tandem with the date arithmetic. For example:

$scope.$watchGroup(['year', 'time'], function (values) {
    var year = values[0], time = values[1];
    $scope.date = new Date(year.getYear(), year.getMonth(), year.getDay(), time.getHours(), time.getMinutes(), time.getSeconds(), time.getMilliseconds());
});

Then you can use date on your scope however you wish, and it will automatically update whenever year or time change.


Note that built-in support for input[type=date] is only available in Angular 1.3.x or later. Earlier versions will not give you access to the date in your model.

Upvotes: 3

Rajeshwar
Rajeshwar

Reputation: 2509

Use the below format.

If hours, minutes, seconds, milliseconds values are not known, give '0' in place of them.

var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);

here the variable 'd' will return the date object, from which you get epoch time also.

Upvotes: 2

Related Questions