How to set a Default Time when Selecting a Date // AngularJS

angular-date

So I started working with AngularJS a few weeks ago to work on an internal project at my workplace. One of the features needed was to make a date range where the user can select a start date and an end date. The requirements also stated that the default time for the start date should be at 00:01 and the default time on the end date should be 23:59.

For the date range I used the bs-datepicker attribute from angular-strap – this library has all the bootstrap elements packaged for angular – and it works great. How did I solve my problem?

First I set set a watch on the ‘StartDate’ and ‘EndDate’ fields.

[code language=”javascript”]
$scope.$watch("StartDate", watchStartDate);
$scope.$watch("EndDate", watchEndDate);
[/code]

 

In the watch function I’m checking that the old value is null or undefined to make sure that it’s the first time the user is setting the date. This checks that if the date is set for the second time, the time isn’t defaulted again to 00:01 or 23:59. Then all you need to do is a simple setHours function on the specified date as follows:

[code language=”javascript”]
///////////////////////
// watch date
///////////////////////
var watchStartDate = function (newvalue, oldvalue) {
if (oldvalue == null || oldvalue == undefined) {
$scope.StartDate.setHours(00, 01, 0);
}
}
var watchEndDate = function (newvalue, oldvalue) {
if (oldvalue == null || oldvalue == undefined) {
$scope.EndDate.setHours(23, 59, 00);
}
}
[/code]

 

Hope this help you in your projects.

(p.s. I’m now having some problems with setting the timezone, once I’ll figure it out, I’ll make another post)

Clive

No Responses

Leave a Reply

Your email address will not be published. Required fields are marked *