Java獲取當天剩餘時間的幾種方法
阿新 • • 發佈:2019-02-19
三種獲取當天剩餘時間的簡潔方式,分別使用DateUtils、DateTime和LocalDateTime,有時間再詳解這三個類的更多方法。下面是編寫的程式碼,有更多好的方式,歡迎留言。
import org.apache.commons.lang.time.DateUtils;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.junit.Test;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util .Calendar;
/**
* Created by Administrator on 2016/12/12.
*/
public class TimeTest {
@Test
public void getTime() {
//方法一
long milliSecondsLeftToday = 86400000 - DateUtils.getFragmentInMilliseconds(Calendar.getInstance(), Calendar.DATE);
long secondsLeftToday = 86400 - DateUtils.getFragmentInSeconds (Calendar.getInstance(), Calendar.DATE);
System.out.println("當天剩餘毫秒1:" + milliSecondsLeftToday);
System.out.println("當天剩餘秒1:" + secondsLeftToday);
//方法二
DateTime dateTime = new DateTime().millisOfDay().withMaximumValue();
long millSeconds2 = new Duration(new DateTime(), dateTime).getMillis ();
long count = new Duration(new DateTime(), dateTime).getStandardSeconds();
System.out.println("當天剩餘毫秒2:" + millSeconds2);
System.out.println("當天剩餘秒2:" + count);
//方法三:LocalDateTime和ChronoUnit為1.8新增
LocalDateTime midnight = LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
long millSeconds = ChronoUnit.MILLIS.between(LocalDateTime.now(),midnight);
long seconds = ChronoUnit.SECONDS.between(LocalDateTime.now(), midnight);
System.out.println("當天剩餘毫秒3:" + millSeconds);
System.out.println("當天剩餘秒3:" + seconds);
}
}