1
votes

I'm hitting a wall on this one. My script finds the difference in hours between 2 dates, however..

var data:Array = ["2011-08-30 11:19:19", "01-09-2011 02"];

var aDate:String = data[0].split(" ")[0];

var dateElements:Array = aDate.split("-");
var date1:Date = new Date();
date1.setDate(int(dateElements[2]));
date1.setMonth(int(dateElements[1])-1);
date1.setFullYear(int(dateElements[0]));
date1.setHours(int(data[0].split(" ")[1].split(":")[0]));

trace("date: " + date1.getDate());
trace("month: " + date1.getMonth());
trace("year: " + date1.getFullYear());
trace("hours: " + date1.getHours());

dateElements = data[1].split(" ")[0].split("-");
var date2:Date = new Date();
date2.setDate(int(dateElements[0]));
date2.setMonth(int(dateElements[1])-1);
date2.setFullYear(int(dateElements[2]));
date2.setHours(int(data[1].split(" ")[1]));

trace("__");
trace("date: " + date2.getDate());
trace("month: " + date2.getMonth());
trace("year: " + date2.getFullYear());
trace("hours: " + date2.getHours());
trace("__");
var elapse:Number = date2.getTime() - date1.getTime();

trace(Math.floor(elapse / 3600000));

As you can see, the date elements trace out the way they should. Now try changing the first element of the data array to "2011-08-31 11:19:19". Although the date elements are fine, the last trace gives a totally weird value. What's even weirder is that when compiling this script a second time in Flash IDE, it takes a long time to compile, then traces nothing at all, as if the script times out.

What's happening here?

1
Can I get an upvote so I can reduce stackoverflow ads ?recursivity

1 Answers

1
votes

If you set the month before you set the date (day) it should give the correct result. By default, when you create a Date object the time is set to the local (Operating System) date. Right now, it's September and it only contains 30 days, so when you set the date to 31 it automatically gets converted to 1. If you define the month as August first it should accept the 31 value. And to avoid february problems it might be a good idea to put the year first.