92

我想创建一个将天数转换为毫秒的函数。天数格式存储为 0.2444,那么如何将其转换为毫秒?

4

8 回答 8

298

在我看来,最好的做法是:

TimeUnit.DAYS.toMillis(1);     // 1 day to milliseconds.
TimeUnit.MINUTES.toMillis(23); // 23 minutes to milliseconds.
TimeUnit.HOURS.toMillis(4);    // 4 hours to milliseconds.
TimeUnit.SECONDS.toMillis(96); // 96 seconds to milliseconds.
于 2014-06-18T12:27:48.570 回答
121

除了其他答案之外,还有TimeUnit类允许您将一个持续时间转换为另一个持续时间。例如,要找出一天有多少毫秒:

TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS); //gives 86400000

请注意,此方法需要 a long,因此如果您有一天的一小部分,则必须将其乘以一天中的毫秒数。

于 2011-08-08T10:00:58.983 回答
23

不够days * 24 * 60 * 60 * 1000吗?

于 2011-08-08T09:56:19.533 回答
13

重要的是要提到,这种方法每 4-5 年可能会出现 1 秒的错误,因为闰秒 ( http://www.nist.gov/pml/div688/leapseconds.cfm ) 和正确的公式因为那一天将是

(24*60*60 + 1) * 1000

有一个问题Calendar 是否支持闰秒?答案是否定的。

因此,如果您正在设计超级时间相关的软件,请注意这个公式。

于 2013-02-27T10:04:54.123 回答
12

24 小时 = 86400 秒 = 86400000 毫秒。只需将您的号码乘以 86400000。

于 2011-08-08T09:57:20.657 回答
3
public static double toMilliSeconds(double day)
{
    return day * 24 * 60 * 60 * 1000;
}

or as long:

public static long toMilliSeconds(double day)
{
    return (long) (day * 24 * 60 * 60 * 1000);
}
于 2011-08-08T10:09:32.710 回答
2

您可以使用此实用程序类 -

public class DateUtils
{
    public static final long SECOND_IN_MILLIS = 1000;
    public static final long MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60;
    public static final long HOUR_IN_MILLIS = MINUTE_IN_MILLIS * 60;
    public static final long DAY_IN_MILLIS = HOUR_IN_MILLIS * 24;
    public static final long WEEK_IN_MILLIS = DAY_IN_MILLIS * 7;
}

如果您正在使用Android 框架,那么只需import将它(也称为DateUtils放在package android.text.format

于 2020-11-05T19:19:24.143 回答
1
int day = 5;
long dayInMilliseconds = day * org.apache.commons.lang.time.DateUtils.MILLIS_PER_DAY
于 2019-05-29T10:15:56.577 回答