2

I am using angular-bootstrap dateandtimepicker module so in below code when user launch browser i want to set date and time 24 hours earlier from currrent date and time , How can i achieve that task using Date object ?

main.html

<ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">
    <datetimepicker data-ng-model="dateRangeStart" data-datetimepicker-config="{ dropdownSelector: '#dropdownStart', renderOn: 'end-date-changed' }" data-on-set-time="startDateOnSetTime()" data-before-render="startDateBeforeRender($dates)"></datetimepicker>
</ul>

ctrl.js

$scope.dateRangeStart = new Date();
$scope.dateRangeStart.setHours($scope.dateRangeStart.getHours() - 24);
console.log($scope.dateRangeStart);
hussain
  • 6,587
  • 18
  • 79
  • 152
  • Possible duplicate of [AngularJS : tomorrow's date and yesterday's date with some ng component](http://stackoverflow.com/questions/31378925/angularjs-tomorrows-date-and-yesterdays-date-with-some-ng-component) – mxr7350 Mar 24 '17 at 16:04
  • What is wrong with your code? What result do you get? What did you expect? Note that not all days are 24 hours long were daylight saving is observed. Possibly a duplicate of [*Add +1 to current date*](http://stackoverflow.com/questions/9989382/add-1-to-current-date). – RobG Mar 24 '17 at 23:14

3 Answers3

3

Js date object is simple and also smart, doesn't just add 24 hours, accounts for daylight savings and new month/year. Just use the following:

var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
nick
  • 789
  • 1
  • 11
  • 27
0

var app = angular.module("app", []); 
app.controller("ctrl", function($scope) {

    var todaysDate = new Date();    
    var tomorrowsDate = new Date().setDate(todaysDate.getDate()+1);    
    var formattedDate = new Date(tomorrowsDate);

    console.log(formattedDate);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
    
</div>
Yolo
  • 1,569
  • 1
  • 11
  • 16
0

You can also use the millisecond value to roll back a whole day from a certain day:

currentDate = new Date();
previousDay = new Date(currentDate - 86400000);
alert(previousDay);