2

I'm fairly new to javascript and angularjs so please bear with me. I am having issues when attempting to interact with the Date object. I assume that Date is a javascript object. However when running .getDate() on a Date object i get a date of 1970.

My code is shown below:

(function() {
  var app = angular.module("app", []);

  var DateController = function($scope) {
        $scope.today = new Date();
        $scope.tomorrow = $scope.today.getDay() +1;
  };

  app.controller("DateController", DateController);
}());

This is really basic, however l do not understand why I am getting that date. I also get the same behavior when working with some other default javascript Date functions. An explanation would also be appreciated.

I have created a plunk for convience: Take me to the plunk!

Sanjeev Singh
  • 3,976
  • 3
  • 33
  • 38
scripton
  • 228
  • 5
  • 15
  • The two answers you have show you the correct way to handle dates. You are getting a date in 1970 because javascript time is measured in milliseconds from midnight January 1, 1970 UTC: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date. So that date is the zero date for Javascript. – Matthew Jaspers Apr 21 '15 at 17:50
  • also, you need to use `getDate()` not `getDay()`, if you are trying to get the entire date – DrCord Apr 21 '15 at 17:50
  • Yeah my bad, i'll change that. I initially meant getDate(), it results in the same outcome though. – scripton Apr 21 '15 at 17:54

2 Answers2

3

Please check this plunker

you should use setDate to change date value

your new controller should be like this:

(function() {
  var app = angular.module("app", []);

  var DateController = function($scope) {
        $scope.today = new Date();
        $scope.tomorrow = new Date();
        $scope.tomorrow = $scope.tomorrow.setDate($scope.tomorrow.getDate() +1);
  };

  app.controller("DateController", DateController);
}());
1

Following from editing your plunk.. more on Date

(function() {
  var app = angular.module("app", []);

  var DateController = function($scope) {
    $scope.today = new Date();

    // elaborated code for illustration
    var nextDay = new Date($scope.today);
    nextDay.setDate($scope.today.getDate()+1);

    $scope.tomorrow = nextDay;
  };

  app.controller("DateController", DateController);
}());

Hope this helps.

daxeh
  • 1,083
  • 8
  • 12
  • Thanks this seems to work just fine, can't believe i missed that! Will mark as you were the first one and + for the reference to the Date object. – scripton Apr 21 '15 at 17:57