0

I want to create a function which calculate the time difference between two times. For example I am sending times as

     timedifference(1 AM,5 PM);

How could I calculate the time difference between 1PM to 5PM? Can anyone help me?

Thanks in advance.

Sachin D
  • 1,370
  • 7
  • 29
  • 42
Swati Singh
  • 1,863
  • 3
  • 19
  • 40

2 Answers2

3

Here is the answer I want:

public static function timeDifference(startTime:Date, endTime:Date) : String
{
    if (startTime == null) { return "startTime empty."; }
    if (endTime   == null) { return "endTime empty."; }
    //trace(" endTime.valueOf() "+endTime.valueOf()+" startTime.valueOf() "+startTime.valueOf())
    var aTms:* = Math.floor(endTime.valueOf() - startTime.valueOf());
    var timeTaken:* =( int(aTms/(    60*60*1000)) %24 );
    //trace(timeTaken);
    return "Time taken:  "  
        + String( int(aTms/(24*60*+60*1000))     ) + " days, "
        + String( int(aTms/(    60*60*1000)) %24 ) + " hours, "
        + String( int(aTms/(       60*1000)) %60 ) + " minutes, "
        + String( int(aTms/(        1*1000)) %60 ) + " seconds.";
}

Usage of this function as:

var myDate:Date = new Date("3/18/2012 10:00 PM");
var myDate1:Date= new Date("3/19/2012 12:00 PM");

timeDifference(myDate,myDate1);
Laurel
  • 5,965
  • 14
  • 31
  • 57
Swati Singh
  • 1,863
  • 3
  • 19
  • 40
1

I asume ur inputting the time at a string since you have AM and PM ... this is a bad idea if you ask me but since that's what you have ill just try to awnser on it.

You would first have to split the string, and add 12 hours if you are on PM, then do time2 - time1 for the difrence...

trace(timedif("1 AM", "3 PM"));

function timedif(string1:String, string2:String){
    var time1 = string1.split(" ");
    var time2 = string2.split(" ");

    var newtime1:int = time1[0];
    var newtime2:int = time2[0];

    if(time1[1] == "PM"){ newtime1 = newtime1 + 12; }
    if(time2[1] == "PM"){ newtime2 = newtime2 + 12; }

    var difrence = newtime2 - newtime1;
    return difrence;
}

I beleive this is the awnser to your question, i'm not saying its a good solution

MakuraYami
  • 3,398
  • 3
  • 16
  • 19