Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Problem and solution of add date into JavaScript with daylightsaving in different time zone

5.00/5 (1 vote)
25 Dec 2011CPOL 15.9K  
Problem and solution of add date into JavaScript with daylightsaving in different time zone
I was facing problems with date time (with the different time zone) in JavaScript. We are setting Tehran time zone with daylight saving into Local machine. At that time, JavaScript date object was creating a problem.

Problem is: when user selects any date, that date is startdate or enddate of daylight and we are adding one day into selected date, then it will return us the same date. Many JQuery calender controls have the same issue:

Example:
JavaScript
// Select Tehran time zome into your local machine
        var currentDate = new Date(2012,02,17);
        // 17-March is a starting day light saving of Tehran time zone
        currentDate = currentDate.setDate(parseInt(currentDate.getDate()) + parseInt(1));
        alert(currentDate);
        // it is returning 17-March-2012


Solution of this problem: I created one function for add days:

JavaScript
// below function is help to add method into date time object
         function add(name, method) {
            if (!Date.prototype[name]) {
              Date.prototype[name] = method;
            }
          };
      
        // below funtion is used for add AddDays function to date time object
        add("addDays", function (num) {
          // two method for adding day
          // Add number of days directly to the passing date
          this.setDate(parseInt(this.getDate()) + parseInt(num));
          // add milisecond to passing date
          //this.setTime(this.getTime() + (num * 86400000));
          return this;
        }); 

        // _daylightSavingAdjust funtion is using to manage time diff for all time zones
        function _daylightSavingAdjust(date) {
            date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
          return date;
        }

        // now you can use daylightsaving with the date object
        // show the result of currentdate without day light saving function in Theran time zone
        var currentDate = new Date(2012,02,17);
        currentDate = currentDate.addDays(1);
        // here you can get value 17-March-2012

        // show the result of currentdate with day light saving function in Theran time zone
        var currentDate = new Date(2012,02,17);
        currentDate = _daylightSavingAdjust(currentDate.addDays(1));
        // here you can get value 18-March-2012


You can do cool stuff on date with JavaScript.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)