2008-10-03 5 views

답변

20

신기원 이래로 두 날짜 시간을 밀리 초로 변환하고 수학을 수행 한 다음 결과 밀리 초를 사용하여 이러한 더 높은 시간 수를 계산할 수 있습니다.

var someDate:Date = new Date(...); 
var anotherDate:Date = new Date(...); 
var millisecondDifference:int = anotherDate.valueOf() - someDate.valueOf(); 
var seconds:int = millisecondDifference/1000; 
.... 

LiveDocs도 이러한 유형의 항목에 유용합니다. ActionScript가 약간 꺼져 있지만 죄송합니다.

이 유형의 수학을 많이 수행하는 경우 이러한 작업을 수행 할 수있는 정적 클래스 메서드 집합을 만드는 것이 좋습니다. 안타깝게도이 기본 기능은 표준 API에는 실제로 존재하지 않습니다.

1

이 작업을 수행하는 자동 방법이 없습니다. 제공된 클래스로 얻을 수있는 가장 좋은 점은 date1.time 및 date2.time을 가져 와서 1970 년 1 월 1 일 이후 두 개의 숫자에 대한 밀리 초 수를 제공하는 것입니다. 그런 다음 이들 사이의 밀리 초 수를 계산할 수 있습니다. 몇 가지 기본 수학을 사용하면 초, 시간, 일 등을 얻을 수 있습니다.

1

정확도를 위해 러셀의 위의 게시물은 25 일 차이가 날 때까지 정확합니다. 그런 다음 숫자가 int에 비해 너무 커집니다 변하기 쉬운. 따라서 millisecondDifference : Number를 선언하십시오.

는 문서화 된 다음 getTime() 및 valueOf() 사이에 약간의 차이가있을 수 있지만, 효과가 나는 것을 채우기 위해 System.TimeSpan 유사한 API와 함께 액션 타임 스팬 클래스를 만들어 그것을

26

를 볼 수 없습니다 그러나 연산자 오버로딩의 부족으로 인해 차이가 있습니다. 당신과 같이 사용할 수 있습니다 : 아래

TimeSpan.fromDates(later, earlier).totalDays; 

클래스에 대한 코드입니다 (큰 게시물에 대한 죄송합니다 - 내가 단위 테스트가 포함되지 않습니다)

/** 
* Represents an interval of time 
*/ 
public class TimeSpan 
{ 
    private var _totalMilliseconds : Number; 

    public function TimeSpan(milliseconds : Number) 
    { 
     _totalMilliseconds = Math.floor(milliseconds); 
    } 

    /** 
    * Gets the number of whole days 
    * 
    * @example In a TimeSpan created from TimeSpan.fromHours(25), 
    *   totalHours will be 1.04, but hours will be 1 
    * @return A number representing the number of whole days in the TimeSpan 
    */ 
    public function get days() : int 
    { 
     return int(_totalMilliseconds/MILLISECONDS_IN_DAY); 
    } 

    /** 
    * Gets the number of whole hours (excluding entire days) 
    * 
    * @example In a TimeSpan created from TimeSpan.fromMinutes(1500), 
    *   totalHours will be 25, but hours will be 1 
    * @return A number representing the number of whole hours in the TimeSpan 
    */ 
    public function get hours() : int 
    { 
     return int(_totalMilliseconds/MILLISECONDS_IN_HOUR) % 24; 
    } 

    /** 
    * Gets the number of whole minutes (excluding entire hours) 
    * 
    * @example In a TimeSpan created from TimeSpan.fromMilliseconds(65500), 
    *   totalSeconds will be 65.5, but seconds will be 5 
    * @return A number representing the number of whole minutes in the TimeSpan 
    */ 
    public function get minutes() : int 
    { 
     return int(_totalMilliseconds/MILLISECONDS_IN_MINUTE) % 60; 
    } 

    /** 
    * Gets the number of whole seconds (excluding entire minutes) 
    * 
    * @example In a TimeSpan created from TimeSpan.fromMilliseconds(65500), 
    *   totalSeconds will be 65.5, but seconds will be 5 
    * @return A number representing the number of whole seconds in the TimeSpan 
    */ 
    public function get seconds() : int 
    { 
     return int(_totalMilliseconds/MILLISECONDS_IN_SECOND) % 60; 
    } 

    /** 
    * Gets the number of whole milliseconds (excluding entire seconds) 
    * 
    * @example In a TimeSpan created from TimeSpan.fromMilliseconds(2123), 
    *   totalMilliseconds will be 2001, but milliseconds will be 123 
    * @return A number representing the number of whole milliseconds in the TimeSpan 
    */ 
    public function get milliseconds() : int 
    { 
     return int(_totalMilliseconds) % 1000; 
    } 

    /** 
    * Gets the total number of days. 
    * 
    * @example In a TimeSpan created from TimeSpan.fromHours(25), 
    *   totalHours will be 1.04, but hours will be 1 
    * @return A number representing the total number of days in the TimeSpan 
    */ 
    public function get totalDays() : Number 
    { 
     return _totalMilliseconds/MILLISECONDS_IN_DAY; 
    } 

    /** 
    * Gets the total number of hours. 
    * 
    * @example In a TimeSpan created from TimeSpan.fromMinutes(1500), 
    *   totalHours will be 25, but hours will be 1 
    * @return A number representing the total number of hours in the TimeSpan 
    */ 
    public function get totalHours() : Number 
    { 
     return _totalMilliseconds/MILLISECONDS_IN_HOUR; 
    } 

    /** 
    * Gets the total number of minutes. 
    * 
    * @example In a TimeSpan created from TimeSpan.fromMilliseconds(65500), 
    *   totalSeconds will be 65.5, but seconds will be 5 
    * @return A number representing the total number of minutes in the TimeSpan 
    */ 
    public function get totalMinutes() : Number 
    { 
     return _totalMilliseconds/MILLISECONDS_IN_MINUTE; 
    } 

    /** 
    * Gets the total number of seconds. 
    * 
    * @example In a TimeSpan created from TimeSpan.fromMilliseconds(65500), 
    *   totalSeconds will be 65.5, but seconds will be 5 
    * @return A number representing the total number of seconds in the TimeSpan 
    */ 
    public function get totalSeconds() : Number 
    { 
     return _totalMilliseconds/MILLISECONDS_IN_SECOND; 
    } 

    /** 
    * Gets the total number of milliseconds. 
    * 
    * @example In a TimeSpan created from TimeSpan.fromMilliseconds(2123), 
    *   totalMilliseconds will be 2001, but milliseconds will be 123 
    * @return A number representing the total number of milliseconds in the TimeSpan 
    */ 
    public function get totalMilliseconds() : Number 
    { 
     return _totalMilliseconds; 
    } 

    /** 
    * Adds the timespan represented by this instance to the date provided and returns a new date object. 
    * @param date The date to add the timespan to 
    * @return A new Date with the offseted time 
    */  
    public function add(date : Date) : Date 
    { 
     var ret : Date = new Date(date.time); 
     ret.milliseconds += totalMilliseconds; 

     return ret; 
    } 

    /** 
    * Creates a TimeSpan from the different between two dates 
    * 
    * Note that start can be after end, but it will result in negative values. 
    * 
    * @param start The start date of the timespan 
    * @param end The end date of the timespan 
    * @return A TimeSpan that represents the difference between the dates 
    * 
    */  
    public static function fromDates(start : Date, end : Date) : TimeSpan 
    { 
     return new TimeSpan(end.time - start.time); 
    } 

    /** 
    * Creates a TimeSpan from the specified number of milliseconds 
    * @param milliseconds The number of milliseconds in the timespan 
    * @return A TimeSpan that represents the specified value 
    */  
    public static function fromMilliseconds(milliseconds : Number) : TimeSpan 
    { 
     return new TimeSpan(milliseconds); 
    } 

    /** 
    * Creates a TimeSpan from the specified number of seconds 
    * @param seconds The number of seconds in the timespan 
    * @return A TimeSpan that represents the specified value 
    */ 
    public static function fromSeconds(seconds : Number) : TimeSpan 
    { 
     return new TimeSpan(seconds * MILLISECONDS_IN_SECOND); 
    } 

    /** 
    * Creates a TimeSpan from the specified number of minutes 
    * @param minutes The number of minutes in the timespan 
    * @return A TimeSpan that represents the specified value 
    */ 
    public static function fromMinutes(minutes : Number) : TimeSpan 
    { 
     return new TimeSpan(minutes * MILLISECONDS_IN_MINUTE); 
    } 

    /** 
    * Creates a TimeSpan from the specified number of hours 
    * @param hours The number of hours in the timespan 
    * @return A TimeSpan that represents the specified value 
    */ 
    public static function fromHours(hours : Number) : TimeSpan 
    { 
     return new TimeSpan(hours * MILLISECONDS_IN_HOUR); 
    } 

    /** 
    * Creates a TimeSpan from the specified number of days 
    * @param days The number of days in the timespan 
    * @return A TimeSpan that represents the specified value 
    */ 
    public static function fromDays(days : Number) : TimeSpan 
    { 
     return new TimeSpan(days * MILLISECONDS_IN_DAY); 
    } 

    /** 
    * The number of milliseconds in one day 
    */ 
    public static const MILLISECONDS_IN_DAY : Number = 86400000; 

    /** 
    * The number of milliseconds in one hour 
    */ 
    public static const MILLISECONDS_IN_HOUR : Number = 3600000; 

    /** 
    * The number of milliseconds in one minute 
    */ 
    public static const MILLISECONDS_IN_MINUTE : Number = 60000; 

    /** 
    * The number of milliseconds in one second 
    */ 
    public static const MILLISECONDS_IN_SECOND : Number = 1000; 
} 
+1

@nchrysler - 내가 다른 사람의 샘플 코드에 기능을 추가하지 않는 것이 좋습니다. 그래도 새로운 기능으로 나만의 답변을 추가 할 수는 있습니다. –

+0

@Erwinus - 흥미 롭다. 내게 책략 진술을 해줄 수 있니? –

+0

라이센스를 추가 할 수 있습니까? 선호 아파치 또는 BSD? 불행히도, 어떤 사람들은 라이센스가 명시되지 않은 한 그것을 사용할 수 없습니다. –

0

ArgumentValidation가 다른 클래스 Szalays는 인식 할 수없는 오류를 발생시키지 않으면 서 각 작업에 적절한 값이 있는지 확인하기 위해 검사를 수행합니다. TimeSpan 클래스를 작동시키는 것은 필수적이지 않으므로 주석 처리 만하면 클래스가 올바르게 작동합니다. 아주 편리합니다하지만 난 그에게 그 아래로 떠날거야으로

리치뿐만 아니라 여기에 인수 유효성 검사 클래스를 게시 할 수 있습니다; P

+0

James는 맞습니다. 소비 코드를 깨끗하게 유지하기위한 유틸리티 클래스 일뿐입니다. –

+0

...이 대답과 sideDoors 대답은 모두 주석이어야합니다.) –

4

이 같은 단일 기능에 대한 내 선호하는 ...[리처드 Szalay의 코드에서 응축]

public function timeDifference(startTime:Date, endTime:Date) : String 
{ 
if (startTime == null) { return "startTime empty."; } 
if (endTime == null) { return "endTime empty."; } 
var aTms = Math.floor(endTime.valueOf() - startTime.valueOf()); 
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."; 
} 
+0

정확하지 않습니다. 윤년 또는 29 일을 가진 2 월을 고려하지 않습니다. –

1
var timeDiff:Number = endDate - startDate; 
var days:Number  = timeDiff/(24*60*60*1000); 
var rem:Number  = int(timeDiff % (24*60*60*1000)); 
var hours:Number = int(rem/(60*60*1000)); 
rem     = int(rem % (60*60*1000)); 
var minutes:Number = int(rem/(60*1000)); 
rem     = int(rem % (60*1000)); 
var seconds:Number = int(rem/1000); 

trace(days + " << >> " +hours+ " << >> " +minutes+ " << >> " +seconds); 

또는

var time:Number = targetDate - currentDate; 
var secs:Number = time/1000; 
var mins:Number = secs/60; 
var hrs:Number = mins/60; 
var days:Number = int(hrs/24); 

secs = int(secs % 60); 
mins = int(mins % 60); 
hrs = int(hrs % 24); 

trace(secs + " << >> " + mins + " << >> " + hrs + " << >> " + days); 
관련 문제