473,387 Members | 1,476 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Calculating a future date

Claus Mygind
571 512MB
I want to take a date value from an input field and calculate a future date (90 days from the input date).

I get inconsistent results.

if I use "1/1/11" I get "4/5/11" or 94 days answer should be "4/1/11".

if I use "3/1/11" I get "6/4/11" or 64 days where the answer should be "6/30/11"

Here is my function:
Expand|Select|Wrap|Line Numbers
  1.     g.inspDate = document.getElementById('inspDate'); 
  2.     g.inspDate.addEventListener("change", function(){
  3.             if (g.process.isDate(this)) 
  4.             {
  5.                 wkDay = new Date(this.value);
  6.                 nextD = wkDay.getDate() +90 ;
  7.                 wkDay.setDate( nextD );
  8.                 document.getElementById("followDate").value = (wkDay.getMonth()+1)+'/'+wkDay.getDay()+'/'+wkDay.getFullYear();
  9.             }
  10.  
  11.         }, false);
  12.  
The g.process.isDate merely allows me to enter either a date with / or - and use either 2 or 4 digit year. The returned result is always a string value "mm/dd/yyyy". This then serves as the input for the function above.

Here is that function but it seems to work just fine. I only include it to show all work used to compute the future date.

Expand|Select|Wrap|Line Numbers
  1.     this.isDate = function (fld) {
  2.         var mo, day, yr;
  3.         var entry = fld.value;
  4.         var reLong = /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/;
  5.         var reShort = /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{2}\b/;
  6.         var valid = (reLong.test(entry)) || (reShort.test(entry));
  7.         if (valid) {
  8.             var delimChar = (entry.indexOf("/") != -1) ? "/" : "-";
  9.             var delim1 = entry.indexOf(delimChar);
  10.             var delim2 = entry.lastIndexOf(delimChar);
  11.             mo = parseInt(entry.substring(0, delim1), 10);
  12.             day = parseInt(entry.substring(delim1+1, delim2), 10);
  13.             yr = parseInt(entry.substring(delim2+1), 10);
  14.             // handle two-digit year
  15.             if (yr < 100) {
  16.                 var today = new Date();
  17.                 // get current century floor (e.g., 2000)
  18.                 var currCent = parseInt(today.getFullYear() / 100) * 100;
  19.                 // two digits up to this year + 15 expands to current century
  20.                 var threshold = (today.getFullYear() + 15) - currCent;
  21.                 if (yr > threshold) {
  22.                     yr += currCent - 100;
  23.                 } else {
  24.                     yr += currCent;
  25.                 }
  26.             }
  27.             var testDate = new Date(yr, mo-1, day);
  28.             if (testDate.getDate() == day) {
  29.                 if (testDate.getMonth() + 1 == mo) {
  30.                     if (testDate.getFullYear() == yr) {
  31.                         // fill field with database-friendly format
  32.                         fld.value = mo + "/" + day + "/" + yr;
  33.                         return true;
  34.                     } else {
  35.                         alert("There is a problem with the year entry.");
  36.                     }
  37.                 } else {
  38.                     alert("There is a problem with the month entry.");
  39.                 }
  40.             } else {
  41.                 alert("There is a problem with the date entry.");
  42.             }
  43.         } else {
  44.             alert("Incorrect date format. Enter as mm/dd/yyyy.");
  45.         }
  46.         return false;
  47.  
  48.     };
  49.  
Aug 26 '11 #1

✓ answered by Claus Mygind

It is sad to see that javaScript has not evolved to include a better date handler. But I finally came up with a solution I found on the web


To bad you have to resort to regExp for simple date handling, but passing the future date calculated using milliseconds as described in my previous reply and passing that date through this at least yields the correct date. ie: dateFormat(<calcDate>,"mm/dd/yyyy");

Expand|Select|Wrap|Line Numbers
  1.     /*
  2.  * Date Format 1.2.3
  3.  * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
  4.  * MIT license
  5.  *
  6.  * Includes enhancements by Scott Trenda <scott.trenda.net>
  7.  * and Kris Kowal <cixar.com/~kris.kowal/>
  8.  *
  9.  * Accepts a date, a mask, or a date and a mask.
  10.  * Returns a formatted version of the given date.
  11.  * The date defaults to the current date/time.
  12.  * The mask defaults to dateFormat.masks.default.
  13.  */
  14.  
  15. var dateFormat = function () {
  16.     var    token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
  17.         timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
  18.         timezoneClip = /[^-+\dA-Z]/g,
  19.         pad = function (val, len) {
  20.             val = String(val);
  21.             len = len || 2;
  22.             while (val.length < len) val = "0" + val;
  23.             return val;
  24.         };
  25.  
  26.     // Regexes and supporting functions are cached through closure
  27.     return function (date, mask, utc) {
  28.         var dF = dateFormat;
  29.  
  30.         // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
  31.         if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
  32.             mask = date;
  33.             date = undefined;
  34.         }
  35.  
  36.         // Passing date through Date applies Date.parse, if necessary
  37.         date = date ? new Date(date) : new Date;
  38.         if (isNaN(date)) throw SyntaxError("invalid date");
  39.  
  40.         mask = String(dF.masks[mask] || mask || dF.masks["default"]);
  41.  
  42.         // Allow setting the utc argument via the mask
  43.         if (mask.slice(0, 4) == "UTC:") {
  44.             mask = mask.slice(4);
  45.             utc = true;
  46.         }
  47.  
  48.         var    _ = utc ? "getUTC" : "get",
  49.             d = date[_ + "Date"](),
  50.             D = date[_ + "Day"](),
  51.             m = date[_ + "Month"](),
  52.             y = date[_ + "FullYear"](),
  53.             H = date[_ + "Hours"](),
  54.             M = date[_ + "Minutes"](),
  55.             s = date[_ + "Seconds"](),
  56.             L = date[_ + "Milliseconds"](),
  57.             o = utc ? 0 : date.getTimezoneOffset(),
  58.             flags = {
  59.                 d:    d,
  60.                 dd:   pad(d),
  61.                 ddd:  dF.i18n.dayNames[D],
  62.                 dddd: dF.i18n.dayNames[D + 7],
  63.                 m:    m + 1,
  64.                 mm:   pad(m + 1),
  65.                 mmm:  dF.i18n.monthNames[m],
  66.                 mmmm: dF.i18n.monthNames[m + 12],
  67.                 yy:   String(y).slice(2),
  68.                 yyyy: y,
  69.                 h:    H % 12 || 12,
  70.                 hh:   pad(H % 12 || 12),
  71.                 H:    H,
  72.                 HH:   pad(H),
  73.                 M:    M,
  74.                 MM:   pad(M),
  75.                 s:    s,
  76.                 ss:   pad(s),
  77.                 l:    pad(L, 3),
  78.                 L:    pad(L > 99 ? Math.round(L / 10) : L),
  79.                 t:    H < 12 ? "a"  : "p",
  80.                 tt:   H < 12 ? "am" : "pm",
  81.                 T:    H < 12 ? "A"  : "P",
  82.                 TT:   H < 12 ? "AM" : "PM",
  83.                 Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
  84.                 o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
  85.                 S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
  86.             };
  87.  
  88.         return mask.replace(token, function ($0) {
  89.             return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
  90.         });
  91.     };
  92. }();
  93.  
  94. // Some common format strings
  95. dateFormat.masks = {
  96.     "default":      "ddd mmm dd yyyy HH:MM:ss",
  97.     shortDate:      "m/d/yy",
  98.     mediumDate:     "mmm d, yyyy",
  99.     longDate:       "mmmm d, yyyy",
  100.     fullDate:       "dddd, mmmm d, yyyy",
  101.     shortTime:      "h:MM TT",
  102.     mediumTime:     "h:MM:ss TT",
  103.     longTime:       "h:MM:ss TT Z",
  104.     isoDate:        "yyyy-mm-dd",
  105.     isoTime:        "HH:MM:ss",
  106.     isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
  107.     isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
  108. };
  109.  
  110. // Internationalization strings
  111. dateFormat.i18n = {
  112.     dayNames: [
  113.         "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
  114.         "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
  115.     ],
  116.     monthNames: [
  117.         "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
  118.         "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
  119.     ]
  120. };
  121.  
  122. // For convenience...
  123. Date.prototype.format = function (mask, utc) {
  124.     return dateFormat(this, mask, utc);
  125. };
  126.  

2 3220
Claus Mygind
571 512MB
Ok I have narrowed the problem down to this code.

document.getElementById("output").value = (wkDay.getMonth()+1)+'/'+wkDay.getDay()+'/'+wkDay.getFullYear();

Here is a simple app which will calculate the future date using milliseconds. That calculation is correct, but when I extract the date information, it returns an incorrect date. This code gives me two different dates 4/1 and 4/5 when tested from 1/1/2011. What am I doing incorrectly?

Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3.  <head>
  4. <script type="text/javascript">
  5.  <!--
  6.     function doMath()
  7.     {
  8.     var input = document.getElementById("input").value
  9.     var today = new Date(input);
  10.     var wkDay = new Date(today.getTime() + 1000 * 60 * 60 * 24 * 90);
  11.     document.getElementById("output").value = (wkDay.getMonth()+1)+'/'+wkDay.getDay()+'/'+wkDay.getFullYear();
  12.     document.getElementById("output2").value = wkDay;
  13.     }
  14.  
  15.  //-->
  16.  </script> </head>
  17.  
  18.  <body>
  19.  Enter date:<input type="text" id="input" value="1/1/2011"/><input type="button" value="Calc 90 days from date" onclick="doMath();" /><br />
  20.  mm/dd/yyyy output <input type="text" id="output" /><br />
  21.  Correct Date output <input type="text" id="output2" size='50'/>
  22.  </body>
  23. </html>
  24.  
I am running the code on XP with FireFox 6.0
Aug 27 '11 #2
Claus Mygind
571 512MB
It is sad to see that javaScript has not evolved to include a better date handler. But I finally came up with a solution I found on the web


To bad you have to resort to regExp for simple date handling, but passing the future date calculated using milliseconds as described in my previous reply and passing that date through this at least yields the correct date. ie: dateFormat(<calcDate>,"mm/dd/yyyy");

Expand|Select|Wrap|Line Numbers
  1.     /*
  2.  * Date Format 1.2.3
  3.  * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
  4.  * MIT license
  5.  *
  6.  * Includes enhancements by Scott Trenda <scott.trenda.net>
  7.  * and Kris Kowal <cixar.com/~kris.kowal/>
  8.  *
  9.  * Accepts a date, a mask, or a date and a mask.
  10.  * Returns a formatted version of the given date.
  11.  * The date defaults to the current date/time.
  12.  * The mask defaults to dateFormat.masks.default.
  13.  */
  14.  
  15. var dateFormat = function () {
  16.     var    token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
  17.         timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
  18.         timezoneClip = /[^-+\dA-Z]/g,
  19.         pad = function (val, len) {
  20.             val = String(val);
  21.             len = len || 2;
  22.             while (val.length < len) val = "0" + val;
  23.             return val;
  24.         };
  25.  
  26.     // Regexes and supporting functions are cached through closure
  27.     return function (date, mask, utc) {
  28.         var dF = dateFormat;
  29.  
  30.         // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
  31.         if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
  32.             mask = date;
  33.             date = undefined;
  34.         }
  35.  
  36.         // Passing date through Date applies Date.parse, if necessary
  37.         date = date ? new Date(date) : new Date;
  38.         if (isNaN(date)) throw SyntaxError("invalid date");
  39.  
  40.         mask = String(dF.masks[mask] || mask || dF.masks["default"]);
  41.  
  42.         // Allow setting the utc argument via the mask
  43.         if (mask.slice(0, 4) == "UTC:") {
  44.             mask = mask.slice(4);
  45.             utc = true;
  46.         }
  47.  
  48.         var    _ = utc ? "getUTC" : "get",
  49.             d = date[_ + "Date"](),
  50.             D = date[_ + "Day"](),
  51.             m = date[_ + "Month"](),
  52.             y = date[_ + "FullYear"](),
  53.             H = date[_ + "Hours"](),
  54.             M = date[_ + "Minutes"](),
  55.             s = date[_ + "Seconds"](),
  56.             L = date[_ + "Milliseconds"](),
  57.             o = utc ? 0 : date.getTimezoneOffset(),
  58.             flags = {
  59.                 d:    d,
  60.                 dd:   pad(d),
  61.                 ddd:  dF.i18n.dayNames[D],
  62.                 dddd: dF.i18n.dayNames[D + 7],
  63.                 m:    m + 1,
  64.                 mm:   pad(m + 1),
  65.                 mmm:  dF.i18n.monthNames[m],
  66.                 mmmm: dF.i18n.monthNames[m + 12],
  67.                 yy:   String(y).slice(2),
  68.                 yyyy: y,
  69.                 h:    H % 12 || 12,
  70.                 hh:   pad(H % 12 || 12),
  71.                 H:    H,
  72.                 HH:   pad(H),
  73.                 M:    M,
  74.                 MM:   pad(M),
  75.                 s:    s,
  76.                 ss:   pad(s),
  77.                 l:    pad(L, 3),
  78.                 L:    pad(L > 99 ? Math.round(L / 10) : L),
  79.                 t:    H < 12 ? "a"  : "p",
  80.                 tt:   H < 12 ? "am" : "pm",
  81.                 T:    H < 12 ? "A"  : "P",
  82.                 TT:   H < 12 ? "AM" : "PM",
  83.                 Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
  84.                 o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
  85.                 S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
  86.             };
  87.  
  88.         return mask.replace(token, function ($0) {
  89.             return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
  90.         });
  91.     };
  92. }();
  93.  
  94. // Some common format strings
  95. dateFormat.masks = {
  96.     "default":      "ddd mmm dd yyyy HH:MM:ss",
  97.     shortDate:      "m/d/yy",
  98.     mediumDate:     "mmm d, yyyy",
  99.     longDate:       "mmmm d, yyyy",
  100.     fullDate:       "dddd, mmmm d, yyyy",
  101.     shortTime:      "h:MM TT",
  102.     mediumTime:     "h:MM:ss TT",
  103.     longTime:       "h:MM:ss TT Z",
  104.     isoDate:        "yyyy-mm-dd",
  105.     isoTime:        "HH:MM:ss",
  106.     isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
  107.     isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
  108. };
  109.  
  110. // Internationalization strings
  111. dateFormat.i18n = {
  112.     dayNames: [
  113.         "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
  114.         "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
  115.     ],
  116.     monthNames: [
  117.         "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
  118.         "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
  119.     ]
  120. };
  121.  
  122. // For convenience...
  123. Date.prototype.format = function (mask, utc) {
  124.     return dateFormat(this, mask, utc);
  125. };
  126.  
Aug 27 '11 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: asreryll | last post by:
I wish to show a future date in a table, so that I can sort and know which case is in need of a review. I can display a future date in a form but I want to see all records that are due on a certain...
28
by: ROSY | last post by:
1.How to make self deletable .exe file such that during runtime the file delete itself from the current path. plz answer, thanks in advence. bye.
6
by: rohayre | last post by:
Im a long time java developer and actually have never done anything with java scripting. I'd like to write a short simple script for calculating a date in the future based on today's date and a...
5
by: Kevin | last post by:
I have a simple application that handles authentication, and one of the things it checks is password aging. If I have something like this: If ("02/14/2007" <= Date.Today.ToString("MM/dd/yyyy"))...
2
by: bloukopkoggelmander | last post by:
Hi all Right, I dont know if this is possible in Access (2007) or not but here goes. I want to create a form for a vehicle delivery where a user completes say half of it before delivery of the...
2
by: =?Utf-8?B?Sm9ubnk=?= | last post by:
I have an ASP.NET 2.0 C# web application that is contacting an Exchange server using WEBDAV. It allows the users to look up appointments for a future date. The problem I have is determining the...
1
by: dkyadav80 | last post by:
Hi Sir, I'm begener in Ajax or Javascript.I have problem about date validation. I have 3 field in html page: 1->date(numeric), 2->month(text 1st 3 letter) 3->year(numeric). I wanna implement to...
4
by: drrajnishpatel via AccessMonster.com | last post by:
Dear Friends i am trying to get a future date as follows, data:1) date of proceeding to leave = D 2) number of days leave sanctioned =N 3) date of reporting for duty =R i grant "n" number of...
7
by: jmartmem | last post by:
Greetings, I have an ASP page with a form (form1) that contains a JavaScript validation function that is activated onSubmit. The function contains a series of IF statements to alert the user to...
7
by: Candace W | last post by:
I need to calculate a date that is 90 days from a hire date, excluding weekends and holidays. From everything I have seen, I need to create a separate table listing the holidays. However, I cannot...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.