从天转换为毫秒

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

133566 次浏览

Won't days * 24 * 60 * 60 * 1000 suffice?

24 hours = 86400 seconds = 86400000 milliseconds. Just multiply your number with 86400000.

In addition to the other answers, there is also the TimeUnit class which allows you to convert one time duration to another. For example, to find out how many milliseconds make up one day:

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

Note that this method takes a long, so if you have a fraction of a day, you will have to multiply it by the number of milliseconds in one day.

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

Its important to mention that once in 4-5 years this method might give a 1 second error, becase of a leap-second (http://www.nist.gov/pml/div688/leapseconds.cfm), and the correct formula for that day would be

(24*60*60 + 1) * 1000

There is a question Are leap seconds catered for by Calendar? and the answer is no.

So, if You're designing super time-dependant software, be careful about this formula.

The best practice for this, in my opinion is:

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.
int day = 5;
long dayInMilliseconds = day * org.apache.commons.lang.time.DateUtils.MILLIS_PER_DAY

You can use this utility class -

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;
}

If you are working on Android framework then just import it (also named DateUtils) under package android.text.format