/    Sign up×
Community /Pin to ProfileBookmark

Problem with date calculation….

I wrote a function to calculate the amount of days that separate two dates. I have to calculate it in milliseconds from the 1st of January 1970 because the dates can be in different month.
Now I found out that the function returns wrong results when the dates are in different month?! Seems like the internal calender of javascript is wrong!? Any advices!?

[CODE]
<HTML>
<HEAD>
<SCRIPT LANGUAGE=”JavaScript”>
var date1 = new Date(2004, 5, 30);
var date2 = new Date(2004, 6, 1);
function difference(){
var dtime = date1.getTime();
var d2time = date2.getTime();
var diff = d2time – dtime;
var diffstring = (diff/1000) + ” seconds”;
diffstring += ” or ” + (diff/(1000*60)) + ” minutes”;
diffstring += ” or ” + (diff/(1000*60*60)) + ” hours”;
diffstring += ” or ” + (diff/(1000*60*60*24)) + ” days”;
document.write(“Timedifference: ” + diffstring);
}
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=”JavaScript”>
difference();
</SCRIPT>
</BODY>
</HTML>
[/CODE]

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@requestcodeMay 27.2004 — If you are trying to get the difference between May 30,2004 and June 1,2004 then you have specified the wrong numbers for the months. Remember that in javascript the months are from 0-11 with zero being January. You were calculating the difference between June 30 and July 1 which would be 1 day or 24 hours.
Copy linkTweet thisAlerts:
@mortyauthorMay 27.2004 — Thanks requestcode!!

This explains the problem I had! Silly mistake! :mad:
×

Success!

Help @morty 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 5.6,
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: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

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