/    Sign up×
Community /Pin to ProfileBookmark

Hi,

how to generate a end date (format: RRRR-MM-DD) from a given date and number of days (as a parameters)

for example: enddate = 2005-05-05 + 5 days (result must be 2005-05-10, but how to generate it with JS?)

thanks

to post a comment
JavaScript

18 Comments(s)

Copy linkTweet thisAlerts:
@scragarMay 05.2005 — var offset = 5;

var enddate = [color=red]([/color]new Date[color=green]()[/color][color=red])[/color].setDate[color=red]([/color][color=green]([/color]new Date[color=blue]()[/color][color=green])[/color].getDate() + offset[color=red])[/color];


color added to make it easier to tell brackets appart.
Copy linkTweet thisAlerts:
@CharlesMay 05.2005 — <script type="text/javascript">
<!--
Date.prototype.toW3CDTF = function () {return [this.getFullYear(), this.getMonth() < 9 ? '0' + (this.getMonth() + 1) : this.getMonth() + 1, this.getDate() < 10 ? '0' + this.getDate() : this.getDate()].join ('-')}

Date.prototype.incrementByDays = function (n) {
this.setDate (this.getDate () + n);
return this;
}

alert (new Date().incrementByDays (5).toW3CDTF ())
// -->
</script>
Copy linkTweet thisAlerts:
@ppysznikauthorMay 05.2005 — it doesn't work...

i wrote something like this:

[SIZE=1]function LZ(x) {return(x<0||x>9?"":"0")+x}



function endDate(date, days)

{

var fromMatch = /^(d{4})-(d{2})-(d{2})$/.exec(date);

fromday = new Date(fromMatch[1], --fromMatch[2], fromMatch[3]);

var enddate = new Date(fromMatch[1], --fromMatch[2], fromMatch[3]).setDate(fromday.getDate() + days);

var y = enddate.getYear()+"";

var M = enddate.getMonth()+1;

var d = enddate.getDate();

var todate = y + "-" + LZ(M) + "-" + LZ(d);

return todate;

}[/SIZE]


it doesn't work too (tells that enddate.getYear() is not a function)...HELP!
Copy linkTweet thisAlerts:
@CharlesMay 05.2005 — tells that enddate.getYear() is not a function[/QUOTE]Strickly speaking Date.getYear() isn't a JavaScript function, not any more. Because of the Y2K problem it was officially removed from the language. Use Date.getFullYear() instead.

Better yet, just use my examply above.
Copy linkTweet thisAlerts:
@CharlesMay 05.2005 — Here's an example that allows you to feed it a date in W3CDTF&lt;script type="text/javascript"&gt;
&lt;!--
Date.fromW3CDTF = function (s) {return (/^(d{4})-(dd?)-(dd?)$/).test(s) ? new Date(RegExp.$1, RegExp.$2 - 1, RegExp.$3) : new Date (s)}

Date.prototype.toW3CDTF = function () {return [this.getFullYear(), this.getMonth() &lt; 9 ? '0' + (this.getMonth() + 1) : this.getMonth() + 1, this.getDate() &lt; 10 ? '0' + this.getDate() : this.getDate()].join ('-')}

Date.prototype.incrementByDays = function (n) {
this.setDate (this.getDate () + n);
return this;
}

alert (new Date.fromW3CDTF('2005-05-09').incrementByDays (5).toW3CDTF ())
// --&gt;
&lt;/script&gt;
Copy linkTweet thisAlerts:
@ppysznikauthorMay 05.2005 — ok, but problem is, that I have to give a second param - startDate, function has to return startDate + days
Copy linkTweet thisAlerts:
@scragarMay 05.2005 — does W3CDTF mean "world wide web consortium date time format"?


charles has acounted for that:

[code=php]alert (new Date.fromW3CDTF('start date').incrementByDays(5).toW3CDTF ())[/code]
Copy linkTweet thisAlerts:
@ppysznikauthorMay 05.2005 — thanks, best regards
Copy linkTweet thisAlerts:
@ppysznikauthorMay 05.2005 — i don't know what is happening but look at this example (build with the code above) and tell me what's wrong..

http://www.ar-media.pl/test/
Copy linkTweet thisAlerts:
@scragarMay 05.2005 — [code=php]<script type="text/javascript">
<!--
Date.fromW3CDTF = function (s) {return (/^(d{4})-(dd?)-(dd?)$/).test(s) ? new Date(RegExp.$1, RegExp.$2 - 1, RegExp.$3) : new Date (s)}

Date.prototype.toW3CDTF = function () {return [this.getFullYear(), this.getMonth() < 9 ? '0' + (this.getMonth() + 1) : this.getMonth() + 1, this.getDate() < 10 ? '0' + this.getDate() : this.getDate()].join ('-')}

Date.prototype.incrementByDays = function (n) {
this.setDate (parseInt(this.getDate()) + n);
return this;
}

alert (new Date.fromW3CDTF('2005-05-09').incrementByDays (5).toW3CDTF ())
// -->
</script>[/code]

We both forgot that getDate returns a string not a number.
Copy linkTweet thisAlerts:
@CharlesMay 05.2005 — From ECMA 262

15.9.1.5 Date Number

A date number is identified by an integer in the range 1 through 31, inclusive.[/quote]
It works just fine as I had it.
Copy linkTweet thisAlerts:
@scragarMay 05.2005 — your right, I had messed something up on my test run ("0"+int = string, must always remember that).

I don't know what wrong with that code then on that link, it sound like it should work...
Copy linkTweet thisAlerts:
@CharlesMay 05.2005 — I accept your surrender on the matter, but just for kicks run the following:&lt;script type="text/javascript"&gt;
&lt;!--
alert (typeof (new Date().getDate()));
// --&gt;
&lt;/script&gt;
Copy linkTweet thisAlerts:
@scragarMay 05.2005 — it returns number, I should have checked that. I found the problem, inputs always return strings, not numbers.


&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;
&lt;html&gt;&lt;head&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;script type="text/javascript"&gt;
&lt;!--
function checkDates(date1, date2)
{
var fromMatch = /^(d{4})-(d{2})-(d{2})$/.exec(date1);
if (fromMatch == null) return false;
var toMatch = /^(d{4})-(d{2})-(d{2})$/.exec(date2);
if (toMatch == null) toMatch = fromMatch;
fromday = new Date(fromMatch[1], --fromMatch[2], fromMatch[3]);
today = new Date(toMatch[1], --toMatch[2], toMatch[3]);
timeLeft = (today.getTime() - fromday.getTime());
if(timeLeft &lt;= 0) return false; else return true;
}

<i> </i>function toDays(date1, date2)
<i> </i>{
<i> </i> var fromMatch = /^(d{4})-(d{2})-(d{2})$/.exec(date1);
<i> </i> var toMatch = /^(d{4})-(d{2})-(d{2})$/.exec(date2);
<i> </i> fromday = new Date(fromMatch[1], --fromMatch[2], fromMatch[3]);
<i> </i> today = new Date(toMatch[1], --toMatch[2], toMatch[3]);
<i> </i> msPerDay = 24 * 60 * 60 * 1000 ;
<i> </i> timeLeft = (today.getTime() - fromday.getTime());
<i> </i> e_daysLeft = timeLeft / msPerDay;
<i> </i> daysLeft = Math.floor(e_daysLeft);
<i> </i> tdays = Math.floor(e_daysLeft);
<i> </i> return daysLeft;
<i> </i>}

<i> </i>Date.fromW3CDTF = function (s) {
<i> </i> return (/^(d{4})-(dd?)-(dd?)$/).test(s) ? new Date(RegExp.$1, RegExp.$2 - 1, RegExp.$3) : new Date (s)
<i> </i>}

<i> </i>Date.prototype.toW3CDTF = function () {
<i> </i> return [this.getFullYear(), this.getMonth() &lt; 9 ? '0' + (this.getMonth() + 1) : this.getMonth() + 1, this.getDate() &lt; 10 ? '0' + this.getDate() : this.getDate()].join ('-')
<i> </i>}

<i> </i>Date.prototype.incrementByDays = function (n) {
<i> </i> this.setDate (this.getDate () + parseInt(n, 10));
<i> </i> return this;
<i> </i>}

//--&gt;
&lt;/script&gt;

&lt;form name="Szukaj_zasobow" method="post" action=""&gt;
&lt;table border="0" cellpadding="0" cellspacing="0" width="232"&gt;
&lt;tr&gt;
&lt;td style="padding: 5px;" align="center" bgcolor="#6ba6e8" valign="top" width="226"&gt;&lt;table border="0" cellpadding="2" cellspacing="0" width="100%"&gt;
&lt;tbody&gt;&lt;tr&gt;
&lt;td class="txtb" align="right"&gt;from&lt;/td&gt;
&lt;td&gt; &lt;input name="od" id="od" size="10" maxlength="10" value="2005-01-01" type="text"&gt; &lt;/td&gt;
&lt;/tr&gt; &lt;tr&gt;
&lt;td class="txtb" align="right"&gt;to&lt;/td&gt;
&lt;td&gt;&lt;input name="dod" id="dod" size="10" maxlength="10" value="" type="text"&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class="txtb" align="right"&gt;days&lt;/td&gt;
&lt;td&gt;&lt;input name="dni" id="dni" size="3" maxlength="3" value="" onchange="if(document.forms['Szukaj_zasobow'].od.value!='') { document.forms['Szukaj_zasobow'].dod.value = new Date.fromW3CDTF(document.forms['Szukaj_zasobow'].od.value).incrementByDays(document.forms['Szukaj_zasobow'].dni.value).toW3CDTF()}" type="text"&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/form&gt;
&lt;/body&gt;&lt;/html&gt;
Copy linkTweet thisAlerts:
@ppysznikauthorMay 05.2005 — thanks

finally, it works, but i had to add parseInt also to "n" parameter

[CODE]
Date.prototype.incrementByDays = function (n) {
this.setDate (parseInt(this.getDate()) + parseInt(n));
return this;
}
[/CODE]
Copy linkTweet thisAlerts:
@scragarMay 05.2005 — you need it only around the n, and you should also specify to base 10.

copy the code from my post.


or at least use this line:

this.setDate (this.getDate () + parseInt(n, 10));
Copy linkTweet thisAlerts:
@CharlesMay 05.2005 — you need it only around the n, and you should also specify to base 10.

copy the code from my post.


or at least use this line:

this.setDate (this.getDate () + parseInt(n, 10));[/QUOTE]
[i]From ECMA 262[/i]
parseInt (string , radix)
The parseInt function produces an integer value dictated by interpretation of the contents of the
string argument according to the specified radix. Leading whitespace in the string is ignored. If radix
is undefined or 0, it is assumed to be 10 except when the number begins with the character pairs 0x
or 0X, in which case a radix of 16 is assumed. Any radix-16 number may also optionally begin with
the character pairs 0x or 0X.
When the parseInt function is called, the following steps are taken:
1. Call ToString(string).
2. Let S be a newly created substring of Result(1) consisting of the first character that is not a
StrWhiteSpaceChar and all characters following that character. (In other words, remove leading
white space.)
3. Let sign be 1.
4. If S is not empty and the first character of S is a minus sign -, let sign be -1.
5. If S is not empty and the first character of S is a plus sign + or a minus sign -, then remove the
first character from S.
6. Let R = ToInt32(radix).
7. If R = 0, go to step 11.
8. If R &lt; 2 or R &gt; 36, then return NaN.
9. If R = 16, go to step 13.
10. Go to step 14.
11. Let R = 10.
12. If the length of S is at least 1 and the first character of S is “0”, then at the implementation's
discretion either let R = 8 or leave R unchanged.
13. If the length of S is at least 2 and the first two characters of S are either “0x” or “0X”, then
remove the first two characters from S and let R = 16.
14. If S contains any character that is not a radix-R digit, then let Z be the substring of S consisting of
all characters before the first such character; otherwise, let Z be S.
15. If Z is empty, return NaN.
16. Compute the mathematical integer value that is represented by Z in radix-R notation, using the
letters A-Z and a-z for digits with values 10 through 35. (However, if R is 10 and Z contains more
than 20 significant digits, every significant digit after the 20th may be replaced by a 0 digit, at
the option of the implementation; and if R is not 2, 4, 8, 10, 16, or 32, then Result(16) may be an
implementation-dependent approximation to the mathematical integer value that is represented by
Z in radix-R notation.)
17. Compute the number value for Result(16).
18. Return sign × Result(17).
Two things follow from this:

1) You don't need that second parameter, in fact you are better off without it.

2) If you pass a number to parseInt it will first be converted into a string and then parseInt will go through the process of converting it back to a number. Using [font=monospace]this.setDate (this.getDate () + Number (n));[/font] will avoid this.
×

Success!

Help @ppysznik spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.29,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...