更新時間:2022-10-31 10:13:21 來源:動力節(jié)點 瀏覽3058次
1. Date 計算時間差
2. 兩 LocalDate 相差年份,返回Integer類型
3. LocalDateTime 計算時間差
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatDemo {
public static void main(String[] args) {
//設置時間格式,為了 能轉(zhuǎn)換成 字符串
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//當前時間
Date beginTime = new Date();
//利用時間格式,把當前時間轉(zhuǎn)為字符串
String start = df.format(beginTime);
//當前時間 轉(zhuǎn)為 長整型 Long
Long begin = beginTime.getTime();
System.out.println("任務開始,開始時間為:"+ start);
int num;
//循環(huán)睡眠 5次,每次 1秒
for(int i = 0; i < 5 ; i++){
num = i +1;
try {
//調(diào)阻塞(睡眠)方法,這里睡眠 1 秒
Thread.sleep(1000);
System.out.println(num+"秒");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//獲取結(jié)束時間
Date finishTime = new Date();
//結(jié)束時間 轉(zhuǎn)為 Long 類型
Long end = finishTime.getTime();
// 時間差 = 結(jié)束時間 - 開始時間,這樣得到的差值是毫秒級別
long timeLag = end - begin;
//天
long day=timeLag/(24*60*60*1000);
//小時
long hour=(timeLag/(60*60*1000)-day*24);
//分鐘
long minute=((timeLag/(60*1000))-day*24*60-hour*60);
//秒,順便說一下,1秒 = 1000毫秒
long s=(timeLag/1000-day*24*60*60-hour*60*60-minute*60);
System.out.println("用了 "+day+"天 "+hour+"時 "+minute+"分 "+s+"秒");
System.out.println("任務結(jié)束,結(jié)束時間為:"+ df.format(finishTime));
}
}
/**
* 傳過來的LocalDate類型的日期,距當前時間,相差多少年
* 可計算年齡,工齡等
* 返回Integer類型的數(shù)
*/
public static Integer getYear(LocalDate date){
//傳過來的日期
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy");
String dateStr = df.format(date);
Long yearLong = Long.parseLong(dateStr);
//當前日期
LocalDate yearNow = LocalDate.now();
String yearNowStr = df.format(yearNow);
Long yearNowLong = Long.parseLong(yearNowStr);
//當前 - 傳過來的參數(shù)
long age = yearNowLong - yearLong;
Integer year = Math.toIntExact(age);
return year;
}
import lombok.extern.slf4j.Slf4j;
import java.time.Duration;
import java.time.LocalDateTime;
/**
* @author 孫永潮
* @date 2022/8/25
*/
@Slf4j
public class LocalDateTimeDemo {
public static void main(String[] args) {
//開始時間
LocalDateTime startTime = LocalDateTime.now();
int num;
//循環(huán)睡眠 3次,每次 1秒
for(int i = 0; i < 3 ; i++){
num = i +1;
try {
//調(diào)阻塞(睡眠)方法,這里睡眠 1 秒
Thread.sleep(1000);
System.out.println(num+"秒");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//結(jié)束時間
LocalDateTime endTime = LocalDateTime.now();
// 獲得兩個時間之間的相差值
Duration dur= Duration.between(startTime, endTime );
//兩個時間差的分鐘數(shù)
long minute = dur.toMinutes();
//納秒
dur.toNanos();
//毫秒
long millisecond = dur.toMillis();
//秒 ( 1秒 = 1000毫秒 )
long s = dur.toMillis()/1000;
//分鐘
dur.toMinutes();
//小時
dur.toHours();
//天數(shù)
dur.toDays();
log.info("用了 {}分", minute);
log.info("用了 {}秒", s);
log.info("用了 {}毫秒", millisecond);
}
}