How can you save time by using the built in Date class?

后端 未结 5 1578
后悔当初
后悔当初 2021-01-07 11:57

The intention of this question is to gather solutions to date / time calculation using the built in Date class instead of writing long complicated functions.

I’ll wr

相关标签:
5条回答
  • 2021-01-07 12:24

    To get the current system date simply create a new Date object without passing any values to the constructor. Like this:

    var today:Date = new Date();
    trace("The date and time right now is: " + today. toLocaleString());
    trace("The date right now is: " + today. toLocaleDateString());
    trace("The time right now is: " + today. toLocaleTimeString());
    
    0 讨论(0)
  • 2021-01-07 12:31

    You can easily find out if a year was a leap year without coding all the exceptions to the rule by using the Date class. By subtracting one day from marts the 1st (requesting marts the 0th), you can find the number of days in February.

    Remember that month is zero-indexed so Marts being the 3rd month has index 2.

    function CheckIfYearIsLeapYear(year:uint):Boolean
    {
        return new Date(year, 2, 0).Date == 29;
    }
    
    0 讨论(0)
  • 2021-01-07 12:36

    The built in Date class handles “overflow” very well, this can be used to add or subtract time. If one of the fields overflows, the date class handles it by adding or subtracting the overflow.

    var date:Date = new Date(1993, 12, 28);
    trace("7 days after the " + date.toLocaleDateString());
    date.setDate(date.Date + 7);
    trace("It was the " + date.toLocaleDateString());
    
    0 讨论(0)
  • 2021-01-07 12:39

    There's also ObjectUtil.dateCompare(a,b)

    0 讨论(0)
  • 2021-01-07 12:44

    To properly compare to dates you need to use the getTime() function, it will give you the time in milliseconds since January 1, 1970. Which makes it easy to compare to dates, a later date will return a larger value.

    You can subtract one from the other to get the difference, but unfortunately there is no built in time span class to handle this cleanly; you will have to use a bit of math to present the difference properly to the user (eg. dividing the difference with the number milliseconds in a day to get the difference in days).

    var date1:Date = new Date(1994, 12, 24);
    var date2:Date = new Date(1991, 1, 3);
    if(date1.getTime() > date2.getTime())
        trace("date1 is after date2");
    else
        trace("date2 is after or the same as date1");
    
    0 讨论(0)
提交回复
热议问题