如何使用内置的 Date 类来节省时间? [英] How can you save time by using the built in Date class?

查看:21
本文介绍了如何使用内置的 Date 类来节省时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题的目的是使用内置的 Date 类来收集日期/时间计算的解决方案,而不是编写冗长的复杂函数.

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 write some answers myself, and accept an answer if anyone comes up with something very clever. But this is mostly meant as a collection of solutions, since I often see overly complicated code for handling dates.

请记住,这不是对于 Date 类无法完成的事情的长期解决方案.

Please remember this is not for long solutions for things the Date class can not do.

一个很好的起点是这里的参考:http://help.adobe.com/en_US/AS3LCR/Flash_10.0/Date.html

A good place to start is the reference found here: http://help.adobe.com/en_US/AS3LCR/Flash_10.0/Date.html

推荐答案

为了正确地与日期进行比较,您需要使用 getTime() 函数,它将为您提供自 1970 年 1 月 1 日以来的时间(以毫秒为单位).这很容易与日期进行比较,较晚的日期将返回更大的值.

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");

这篇关于如何使用内置的 Date 类来节省时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆