記錄Java基礎(chǔ)-常用API-有關(guān)時間日期的類。
1 Date類
1.1 什么是Date類
- Date 類位于 java.util 包中,代表當(dāng)前所在系統(tǒng)的日期時間信息或表示特定的瞬間,精確到毫秒。
- 這個類在早期版本的 Java 中被廣泛使用,但由于其功能和設(shè)計(jì)的局限性,自Java8起,推薦使用 java.time 包中的新日期和時間 API(如 LocalDate、LocalTime、LocalDateTime 等)。
1.2 Date 類的主要特點(diǎn):
- 不可變對象:一旦創(chuàng)建了 Date 對象,其值就不能更改。
- 線程安全:Date 類是線程安全的,因?yàn)樗拇蠖鄶?shù)方法都是同步的。
- 與平臺無關(guān):無論運(yùn)行 Java 程序的系統(tǒng)是什么,Date 類都表示同樣的時間單位。
1.3 主要方法:
- 構(gòu)造函數(shù):創(chuàng)建新的 Date 對象。
Date date = new Date(); // 當(dāng)前日期和時間
Date date = new Date(long date); // 在給定的時間戳上創(chuàng)建日期對象
- 獲取時間單位:返回給定時間單位的值。
public long getTime() // 返回自1970年1月1日以來的毫秒數(shù)
public int getYear() // 返回年份(基于1900年)
public int getMonth() // 返回月份(0-11)
public int getDay() // 返回日(1-31)
- 設(shè)置時間單位:設(shè)置給定時間單位的值。
public void setYear(int year) // 設(shè)置年份(基于1900年)
public void setMonth(int month) // 設(shè)置月份(0-11)
public void setDay(int day) // 設(shè)置日(1-31)
- 其他常用方法:如 after(), before(), equals(), hashCode() 等。
import java.util.Date;
public class DateExample {
public static void main(String[] args) {
// 獲取當(dāng)前日期和時間
Date currentDate = new Date();
System.out.println("當(dāng)前日期和時間: " + currentDate);
// 截取日期年/月/日
System.out.println("年: " + currentDate.getYear());
System.out.println("月: " + currentDate.getMonth());
System.out.println("日: " + currentDate.getDate());
// 設(shè)置日期組件(注意:這些方法已被棄用)
currentDate.setYear(2023); // 設(shè)置年份(基于1900年)
currentDate.setMonth(6); // 設(shè)置月份(0-11)代表七月
currentDate.setDate(23); // 設(shè)置日(1-31)
System.out.println("設(shè)置后的日期和時間: " + currentDate);
}
}
2 java8新增日期類
2.1 LocalDate、LocalTime、LocalDateTime類
2.2 Instant時間戳
2.3 DateTimeFormatter
2.4 日期間隔Period、時間間隔Duration
文章來源:http://www.zghlxwxcb.cn/news/detail-815724.html
2.5 全類型時間間隔ChronoUnit
文章來源地址http://www.zghlxwxcb.cn/news/detail-815724.html
到了這里,關(guān)于【自學(xué)筆記】01Java基礎(chǔ)-08Java常用API:03日期類詳解的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!