Java時(shí)間處理詳細(xì)教程與最佳實(shí)踐案例
Java時(shí)間處理詳細(xì)教程與代碼案例
一、基礎(chǔ)概念
1. 時(shí)間與日期基本概念
時(shí)區(qū)(TimeZone):地球被劃分為24個(gè)時(shí)區(qū),每個(gè)時(shí)區(qū)相差1小時(shí)。Java中使用ZoneId表示時(shí)區(qū)。
時(shí)間戳(Timestamp):從1970年1月1日00:00:00 GMT開(kāi)始的毫秒數(shù),Java中用Instant類(lèi)表示。
本地日期時(shí)間(LocalDateTime):不包含時(shí)區(qū)信息的日期和時(shí)間,Java中用LocalDateTime類(lèi)表示。
時(shí)間格式(DateTime Format):用于日期時(shí)間的顯示和解析,如"yyyy-MM-dd HH:mm:ss"。
二、傳統(tǒng)日期時(shí)間API
1. java.util.Date類(lèi)
// 創(chuàng)建當(dāng)前時(shí)間的Date對(duì)象
Date now = new Date();
System.out.println("當(dāng)前時(shí)間: " + now);
// 創(chuàng)建指定時(shí)間的Date對(duì)象
Date specificDate = new Date(121, 6, 15); // 2021年7月15日(年份從1900開(kāi)始,月份從0開(kāi)始)
System.out.println("指定時(shí)間: " + specificDate);
// 獲取時(shí)間戳
long timestamp = now.getTime();
System.out.println("時(shí)間戳: " + timestamp);
// 比較兩個(gè)Date對(duì)象
System.out.println("比較結(jié)果: " + now.compareTo(specificDate));2. java.util.Calendar類(lèi)
// 獲取Calendar實(shí)例
Calendar calendar = Calendar.getInstance();
System.out.println("當(dāng)前時(shí)間: " + calendar.getTime());
// 設(shè)置特定日期
calendar.set(2023, Calendar.JULY, 31, 14, 30, 0);
System.out.println("設(shè)置后的時(shí)間: " + calendar.getTime());
// 獲取特定字段
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1; // 月份從0開(kāi)始
int day = calendar.get(Calendar.DAY_OF_MONTH);
System.out.printf("%d年%d月%d日\(chéng)n", year, month, day);
// 日期計(jì)算
calendar.add(Calendar.DAY_OF_MONTH, 5); // 加5天
System.out.println("加5天后的時(shí)間: " + calendar.getTime());3. java.text.SimpleDateFormat
// 創(chuàng)建SimpleDateFormat實(shí)例
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 格式化日期
String formattedDate = sdf.format(new Date());
System.out.println("格式化后的日期: " + formattedDate);
// 解析日期字符串
try {
Date parsedDate = sdf.parse("2023-07-31 15:30:00");
System.out.println("解析后的日期: " + parsedDate);
} catch (ParseException e) {
e.printStackTrace();
}
// 線(xiàn)程安全的格式化方式
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String result = df.format(new Date());三、Java 8新日期時(shí)間API
1. java.time包概述
Java 8引入了全新的日期時(shí)間API,位于java.time包中,主要類(lèi)包括:
Instant- 時(shí)間戳LocalDate- 不含時(shí)間的日期LocalTime- 不含日期的時(shí)間LocalDateTime- 不含時(shí)區(qū)的日期時(shí)間ZonedDateTime- 帶時(shí)區(qū)的日期時(shí)間Period- 日期區(qū)間Duration- 時(shí)間區(qū)間
2. 主要類(lèi)介紹
LocalDate
// 獲取當(dāng)前日期
LocalDate today = LocalDate.now();
System.out.println("當(dāng)前日期: " + today);
// 創(chuàng)建特定日期
LocalDate specificDate = LocalDate.of(2023, Month.JULY, 31);
System.out.println("指定日期: " + specificDate);
// 從字符串解析
LocalDate parsedDate = LocalDate.parse("2023-07-31");
System.out.println("解析的日期: " + parsedDate);
// 獲取日期字段
System.out.println("年: " + today.getYear());
System.out.println("月: " + today.getMonthValue());
System.out.println("日: " + today.getDayOfMonth());
System.out.println("星期: " + today.getDayOfWeek());LocalTime
// 獲取當(dāng)前時(shí)間
LocalTime now = LocalTime.now();
System.out.println("當(dāng)前時(shí)間: " + now);
// 創(chuàng)建特定時(shí)間
LocalTime specificTime = LocalTime.of(14, 30, 45);
System.out.println("指定時(shí)間: " + specificTime);
// 從字符串解析
LocalTime parsedTime = LocalTime.parse("15:30:00");
System.out.println("解析的時(shí)間: " + parsedTime);
// 獲取時(shí)間字段
System.out.println("時(shí): " + now.getHour());
System.out.println("分: " + now.getMinute());
System.out.println("秒: " + now.getSecond());LocalDateTime
// 獲取當(dāng)前日期時(shí)間
LocalDateTime now = LocalDateTime.now();
System.out.println("當(dāng)前日期時(shí)間: " + now);
// 創(chuàng)建特定日期時(shí)間
LocalDateTime specificDateTime = LocalDateTime.of(2023, Month.JULY, 31, 14, 30, 45);
System.out.println("指定日期時(shí)間: " + specificDateTime);
// 從LocalDate和LocalTime組合
LocalDateTime combinedDateTime = LocalDateTime.of(LocalDate.now(), LocalTime.now());
System.out.println("組合的日期時(shí)間: " + combinedDateTime);
// 獲取字段
System.out.println("年: " + now.getYear());
System.out.println("時(shí): " + now.getHour());ZonedDateTime
// 獲取當(dāng)前時(shí)區(qū)的日期時(shí)間
ZonedDateTime now = ZonedDateTime.now();
System.out.println("當(dāng)前時(shí)區(qū)日期時(shí)間: " + now);
// 創(chuàng)建特定時(shí)區(qū)的日期時(shí)間
ZoneId tokyoZone = ZoneId.of("Asia/Tokyo");
ZonedDateTime tokyoTime = ZonedDateTime.now(tokyoZone);
System.out.println("東京時(shí)間: " + tokyoTime);
// 時(shí)區(qū)轉(zhuǎn)換
ZonedDateTime newYorkTime = now.withZoneSameInstant(ZoneId.of("America/New_York"));
System.out.println("紐約時(shí)間: " + newYorkTime);Instant
// 獲取當(dāng)前時(shí)間戳
Instant now = Instant.now();
System.out.println("當(dāng)前時(shí)間戳: " + now);
// 從毫秒數(shù)創(chuàng)建
Instant specificInstant = Instant.ofEpochMilli(1690800000000L);
System.out.println("指定時(shí)間戳: " + specificInstant);
// 轉(zhuǎn)換為L(zhǎng)ocalDateTime
LocalDateTime localDateTime = LocalDateTime.ofInstant(now, ZoneId.systemDefault());
System.out.println("轉(zhuǎn)換為本地日期時(shí)間: " + localDateTime);3. 日期時(shí)間操作
// 日期時(shí)間計(jì)算
LocalDateTime now = LocalDateTime.now();
System.out.println("當(dāng)前時(shí)間: " + now);
// 加3天
LocalDateTime plusDays = now.plusDays(3);
System.out.println("加3天: " + plusDays);
// 減2小時(shí)
LocalDateTime minusHours = now.minusHours(2);
System.out.println("減2小時(shí): " + minusHours);
// 加6個(gè)月
LocalDateTime plusMonths = now.plusMonths(6);
System.out.println("加6個(gè)月: " + plusMonths);
// 使用Period和Duration
Period period = Period.ofDays(5);
Duration duration = Duration.ofHours(3);
LocalDateTime result1 = now.plus(period);
LocalDateTime result2 = now.plus(duration);
System.out.println("加5天: " + result1);
System.out.println("加3小時(shí): " + result2);4. 格式化與解析
// 創(chuàng)建DateTimeFormatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 格式化
String formattedDateTime = LocalDateTime.now().format(formatter);
System.out.println("格式化后的日期時(shí)間: " + formattedDateTime);
// 解析
LocalDateTime parsedDateTime = LocalDateTime.parse("2023-07-31 15:30:00", formatter);
System.out.println("解析后的日期時(shí)間: " + parsedDateTime);
// 預(yù)定義的格式
DateTimeFormatter isoFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
String isoFormatted = LocalDateTime.now().format(isoFormatter);
System.out.println("ISO格式: " + isoFormatted);四、時(shí)間轉(zhuǎn)換與計(jì)算
1. 新舊API轉(zhuǎn)換
// Date轉(zhuǎn)Instant
Date date = new Date();
Instant instant = date.toInstant();
System.out.println("Date轉(zhuǎn)Instant: " + instant);
// Instant轉(zhuǎn)Date
Date newDate = Date.from(instant);
System.out.println("Instant轉(zhuǎn)Date: " + newDate);
// Calendar轉(zhuǎn)ZonedDateTime
Calendar calendar = Calendar.getInstance();
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(calendar.toInstant(), calendar.getTimeZone().toZoneId());
System.out.println("Calendar轉(zhuǎn)ZonedDateTime: " + zonedDateTime);
// ZonedDateTime轉(zhuǎn)Calendar
Calendar newCalendar = Calendar.getInstance();
newCalendar.clear();
newCalendar.setTime(Date.from(zonedDateTime.toInstant()));
System.out.println("ZonedDateTime轉(zhuǎn)Calendar: " + newCalendar.getTime());2. 時(shí)區(qū)處理
// 獲取所有可用時(shí)區(qū)
Set<String> allZones = ZoneId.getAvailableZoneIds();
System.out.println("所有時(shí)區(qū)數(shù)量: " + allZones.size());
// 時(shí)區(qū)轉(zhuǎn)換
ZonedDateTime now = ZonedDateTime.now();
System.out.println("當(dāng)前時(shí)區(qū)時(shí)間: " + now);
ZonedDateTime londonTime = now.withZoneSameInstant(ZoneId.of("Europe/London"));
System.out.println("倫敦時(shí)間: " + londonTime);
ZonedDateTime newYorkTime = now.withZoneSameInstant(ZoneId.of("America/New_York"));
System.out.println("紐約時(shí)間: " + newYorkTime);
// 夏令時(shí)檢查
ZoneId londonZone = ZoneId.of("Europe/London");
ZonedDateTime summerTime = ZonedDateTime.of(2023, 6, 15, 12, 0, 0, 0, londonZone);
ZonedDateTime winterTime = ZonedDateTime.of(2023, 12, 15, 12, 0, 0, 0, londonZone);
System.out.println("倫敦夏令時(shí)偏移: " + summerTime.getOffset());
System.out.println("倫敦冬令時(shí)偏移: " + winterTime.getOffset());3. 時(shí)間差計(jì)算
// 計(jì)算兩個(gè)LocalDate之間的Period
LocalDate startDate = LocalDate.of(2023, 1, 1);
LocalDate endDate = LocalDate.of(2023, 7, 31);
Period period = Period.between(startDate, endDate);
System.out.printf("日期差: %d年%d個(gè)月%d天\n",
period.getYears(), period.getMonths(), period.getDays());
// 計(jì)算兩個(gè)LocalTime之間的Duration
LocalTime startTime = LocalTime.of(8, 30);
LocalTime endTime = LocalTime.of(17, 45);
Duration duration = Duration.between(startTime, endTime);
System.out.println("時(shí)間差: " + duration.toHours() + "小時(shí)" +
(duration.toMinutes() % 60) + "分鐘");
// 使用ChronoUnit
long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);
System.out.println("相差天數(shù): " + daysBetween);
long hoursBetween = ChronoUnit.HOURS.between(startTime, endTime);
System.out.println("相差小時(shí)數(shù): " + hoursBetween);五、高級(jí)應(yīng)用
1. 工作日計(jì)算
// 計(jì)算工作日(排除周末)
LocalDate startDate = LocalDate.of(2023, 7, 1); // 7月1日是星期六
LocalDate endDate = LocalDate.of(2023, 7, 31);
long workingDays = startDate.datesUntil(endDate)
.filter(date -> date.getDayOfWeek() != DayOfWeek.SATURDAY &&
date.getDayOfWeek() != DayOfWeek.SUNDAY)
.count();
System.out.println("7月工作日天數(shù): " + workingDays);
// 使用TemporalAdjusters
LocalDate nextWorkingDay = LocalDate.now().with(TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY));
System.out.println("下一個(gè)工作日: " + nextWorkingDay);2. 定時(shí)任務(wù)與時(shí)間處理
// 使用Timer/TimerTask
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("定時(shí)任務(wù)執(zhí)行: " + LocalTime.now());
}
}, 0, 1000); // 立即開(kāi)始,每隔1秒執(zhí)行一次
// 5秒后取消定時(shí)任務(wù)
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
timer.cancel();
// 使用ScheduledExecutorService
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(
() -> System.out.println("調(diào)度任務(wù)執(zhí)行: " + LocalTime.now()),
0, 1, TimeUnit.SECONDS);
// 5秒后關(guān)閉
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
executor.shutdown();3. 數(shù)據(jù)庫(kù)時(shí)間處理
// JDBC與java.time類(lèi)型映射
// 假設(shè)有PreparedStatement ps和ResultSet rs
// 寫(xiě)入數(shù)據(jù)庫(kù)
LocalDateTime now = LocalDateTime.now();
ps.setObject(1, now); // 直接使用setObject
// 從數(shù)據(jù)庫(kù)讀取
LocalDateTime dbDateTime = rs.getObject("date_column", LocalDateTime.class);
// JPA/Hibernate實(shí)體類(lèi)中的時(shí)間字段
/*
@Entity
public class Event {
@Id
private Long id;
@Column
private LocalDateTime eventTime;
@Column
private LocalDate eventDate;
// getters and setters
}
*/4. 序列化與反序列化
// JSON中的時(shí)間處理(使用Jackson)
ObjectMapper mapper = new ObjectMapper();
// 注冊(cè)JavaTimeModule以支持java.time類(lèi)型
mapper.registerModule(new JavaTimeModule());
// 禁用時(shí)間戳格式
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
Event event = new Event();
event.setEventTime(LocalDateTime.now());
// 序列化
String json = mapper.writeValueAsString(event);
System.out.println("JSON: " + json);
// 反序列化
Event parsedEvent = mapper.readValue(json, Event.class);
System.out.println("解析后的時(shí)間: " + parsedEvent.getEventTime());六、最佳實(shí)踐與常見(jiàn)問(wèn)題
1. 線(xiàn)程安全最佳實(shí)踐
// 傳統(tǒng)API不是線(xiàn)程安全的
SimpleDateFormat unsafeFormat = new SimpleDateFormat("yyyy-MM-dd");
// 解決方案1:每次創(chuàng)建新實(shí)例
SimpleDateFormat safeFormat1 = new SimpleDateFormat("yyyy-MM-dd");
// 解決方案2:使用ThreadLocal
private static final ThreadLocal<SimpleDateFormat> threadLocalFormat =
ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
SimpleDateFormat safeFormat2 = threadLocalFormat.get();
// Java 8 API是線(xiàn)程安全的,可以共享實(shí)例
DateTimeFormatter safeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");2. 性能優(yōu)化建議
// 重用DateTimeFormatter實(shí)例
private static final DateTimeFormatter FORMATTER =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 批量格式化日期時(shí)間
List<LocalDateTime> dateTimes = List.of(
LocalDateTime.now(),
LocalDateTime.now().plusDays(1),
LocalDateTime.now().plusDays(2)
);
List<String> formattedDates = dateTimes.stream()
.map(FORMATTER::format)
.collect(Collectors.toList());
System.out.println("格式化后的日期列表: " + formattedDates);3. 常見(jiàn)陷阱與解決方案
// 陷阱1:月份從0開(kāi)始(傳統(tǒng)API)
Calendar calendar = Calendar.getInstance();
calendar.set(2023, 6, 31); // 實(shí)際上是7月31日
System.out.println("月份陷阱: " + calendar.getTime());
// 解決方案:使用常量
calendar.set(2023, Calendar.JULY, 31);
// 陷阱2:SimpleDateFormat的線(xiàn)程安全問(wèn)題
// 解決方案:如前面所述,使用ThreadLocal或每次創(chuàng)建新實(shí)例
// 陷阱3:時(shí)區(qū)忽略
LocalDateTime localDateTime = LocalDateTime.now();
ZonedDateTime zonedDateTime = ZonedDateTime.now();
System.out.println("LocalDateTime: " + localDateTime);
System.out.println("ZonedDateTime: " + zonedDateTime);
// 解決方案:明確使用時(shí)區(qū)
ZonedDateTime correctZoned = localDateTime.atZone(ZoneId.systemDefault());4. 國(guó)際化注意事項(xiàng)
// 本地化日期格式
Locale usLocale = Locale.US;
Locale chinaLocale = Locale.CHINA;
DateTimeFormatter usFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(usLocale);
DateTimeFormatter chinaFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(chinaLocale);
ZonedDateTime now = ZonedDateTime.now();
System.out.println("美國(guó)格式: " + now.format(usFormatter));
System.out.println("中國(guó)格式: " + now.format(chinaFormatter));
// 本地化星期和月份名稱(chēng)
String dayName = now.getDayOfWeek().getDisplayName(TextStyle.FULL, chinaLocale);
String monthName = now.getMonth().getDisplayName(TextStyle.FULL, chinaLocale);
System.out.println("中文星期: " + dayName);
System.out.println("中文月份: " + monthName);七、擴(kuò)展學(xué)習(xí)
1. Joda-Time庫(kù)簡(jiǎn)介
// Joda-Time的基本使用(如果項(xiàng)目中已添加依賴(lài))
/*
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.10</version>
</dependency>
*/
// 創(chuàng)建DateTime實(shí)例
org.joda.time.DateTime jodaDateTime = new org.joda.time.DateTime();
System.out.println("Joda-Time當(dāng)前時(shí)間: " + jodaDateTime);
// 日期計(jì)算
org.joda.time.DateTime plusDays = jodaDateTime.plusDays(3);
System.out.println("加3天: " + plusDays);
// 格式化
org.joda.time.format.DateTimeFormatter jodaFormatter =
org.joda.time.format.DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
System.out.println("格式化: " + jodaFormatter.print(jodaDateTime));2. ThreeTen-Extra項(xiàng)目
// ThreeTen-Extra提供了額外的日期時(shí)間類(lèi)
/*
<dependency>
<groupId>org.threeten</groupId>
<artifactId>threeten-extra</artifactId>
<version>1.7.0</version>
</dependency>
*/
// 使用Interval類(lèi)
org.threeten.extra.Interval interval =
org.threeten.extra.Interval.of(
Instant.now(),
Instant.now().plusSeconds(3600));
System.out.println("Interval時(shí)長(zhǎng): " + interval.toDuration().getSeconds() + "秒");
// 使用YearQuarter類(lèi)
org.threeten.extra.YearQuarter yearQuarter =
org.threeten.extra.YearQuarter.now();
System.out.println("當(dāng)前季度: " + yearQuarter);八、實(shí)戰(zhàn)項(xiàng)目
1. 開(kāi)發(fā)一個(gè)時(shí)間工具類(lèi)
public class DateTimeUtils {
private static final DateTimeFormatter DEFAULT_FORMATTER =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 獲取當(dāng)前時(shí)間字符串
public static String now() {
return LocalDateTime.now().format(DEFAULT_FORMATTER);
}
// 計(jì)算兩個(gè)日期之間的工作日
public static long calculateWorkingDays(LocalDate start, LocalDate end) {
return start.datesUntil(end)
.filter(date -> date.getDayOfWeek() != DayOfWeek.SATURDAY &&
date.getDayOfWeek() != DayOfWeek.SUNDAY)
.count();
}
// 時(shí)區(qū)轉(zhuǎn)換
public static ZonedDateTime convertTimezone(ZonedDateTime dateTime, String zoneId) {
return dateTime.withZoneSameInstant(ZoneId.of(zoneId));
}
// 測(cè)試工具類(lèi)
public static void main(String[] args) {
System.out.println("當(dāng)前時(shí)間: " + DateTimeUtils.now());
LocalDate start = LocalDate.of(2023, 7, 1);
LocalDate end = LocalDate.of(2023, 7, 31);
System.out.println("工作日天數(shù): " + calculateWorkingDays(start, end));
ZonedDateTime now = ZonedDateTime.now();
System.out.println("紐約時(shí)間: " + convertTimezone(now, "America/New_York"));
}
}2. 實(shí)現(xiàn)一個(gè)工作日計(jì)算器
public class WorkingDayCalculator {
private final Set<LocalDate> holidays;
public WorkingDayCalculator() {
this.holidays = new HashSet<>();
}
public void addHoliday(LocalDate date) {
holidays.add(date);
}
public long calculateWorkingDays(LocalDate start, LocalDate end) {
return start.datesUntil(end)
.filter(this::isWorkingDay)
.count();
}
private boolean isWorkingDay(LocalDate date) {
return date.getDayOfWeek() != DayOfWeek.SATURDAY &&
date.getDayOfWeek() != DayOfWeek.SUNDAY &&
!holidays.contains(date);
}
public static void main(String[] args) {
WorkingDayCalculator calculator = new WorkingDayCalculator();
// 添加2023年國(guó)慶假期
calculator.addHoliday(LocalDate.of(2023, 10, 1));
calculator.addHoliday(LocalDate.of(2023, 10, 2));
calculator.addHoliday(LocalDate.of(2023, 10, 3));
LocalDate start = LocalDate.of(2023, 10, 1);
LocalDate end = LocalDate.of(2023, 10, 7);
long workingDays = calculator.calculateWorkingDays(start, end);
System.out.println("2023年國(guó)慶假期期間的工作日天數(shù): " + workingDays);
}
}3. 構(gòu)建一個(gè)跨時(shí)區(qū)會(huì)議系統(tǒng)的時(shí)間處理模塊
public class MeetingScheduler {
private final Map<String, ZoneId> participantTimeZones;
public MeetingScheduler() {
this.participantTimeZones = new HashMap<>();
}
public void addParticipant(String name, String timeZone) {
participantTimeZones.put(name, ZoneId.of(timeZone));
}
public Map<String, ZonedDateTime> scheduleMeeting(String organizer, LocalDateTime localTime) {
ZoneId organizerZone = participantTimeZones.get(organizer);
if (organizerZone == null) {
throw new IllegalArgumentException("Organizer not found");
}
ZonedDateTime organizerTime = ZonedDateTime.of(localTime, organizerZone);
Map<String, ZonedDateTime> times = new HashMap<>();
for (Map.Entry<String, ZoneId> entry : participantTimeZones.entrySet()) {
String participant = entry.getKey();
ZoneId zone = entry.getValue();
times.put(participant, organizerTime.withZoneSameInstant(zone));
}
return times;
}
public static void main(String[] args) {
MeetingScheduler scheduler = new MeetingScheduler();
// 添加參與者
scheduler.addParticipant("Alice", "America/New_York");
scheduler.addParticipant("Bob", "Europe/London");
scheduler.addParticipant("Charlie", "Asia/Tokyo");
scheduler.addParticipant("David", "Australia/Sydney");
// Alice在紐約安排會(huì)議時(shí)間為2023-07-31 14:00
LocalDateTime meetingTime = LocalDateTime.of(2023, 7, 31, 14, 0);
Map<String, ZonedDateTime> schedule = scheduler.scheduleMeeting("Alice", meetingTime);
// 打印各參與者的本地時(shí)間
schedule.forEach((name, time) -> {
System.out.printf("%s的本地會(huì)議時(shí)間: %s %s\n",
name,
time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")),
time.getZone());
});
}
}這個(gè)完整的Java時(shí)間處理教程涵蓋了從基礎(chǔ)概念到高級(jí)應(yīng)用的各個(gè)方面,并提供了豐富的代碼示例。您可以根據(jù)自己的需求選擇相應(yīng)的部分進(jìn)行學(xué)習(xí)和實(shí)踐。
到此這篇關(guān)于Java時(shí)間處理詳細(xì)教程與最佳實(shí)踐案例的文章就介紹到這了,更多相關(guān)java時(shí)間處理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Java前后端時(shí)間處理全攻略(從格式化到時(shí)區(qū)轉(zhuǎn)換)
- Java處理時(shí)間格式CST和GMT轉(zhuǎn)換方法示例
- Java對(duì)世界不同時(shí)區(qū)timezone之間時(shí)間轉(zhuǎn)換的處理方法
- Java中實(shí)現(xiàn)時(shí)間類(lèi)型轉(zhuǎn)換的代碼詳解
- Java日期毫秒值和常見(jiàn)日期時(shí)間格式相互轉(zhuǎn)換方法
- java轉(zhuǎn)換時(shí)區(qū)時(shí)間過(guò)程詳解
- java實(shí)現(xiàn)的日期時(shí)間轉(zhuǎn)換工具類(lèi)完整示例
- Java日期時(shí)間字符串和毫秒相互轉(zhuǎn)換的方法
相關(guān)文章
Java實(shí)現(xiàn)父子線(xiàn)程共享數(shù)據(jù)的幾種方法
本文主要介紹了Java實(shí)現(xiàn)父子線(xiàn)程共享數(shù)據(jù)的幾種方法,包括直接共享變量、使用?ThreadLocal、同步機(jī)制、線(xiàn)程安全的數(shù)據(jù)結(jié)構(gòu)以及ExecutorService,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2025-04-04
SpringMVC自定義攔截器實(shí)現(xiàn)過(guò)程詳解
這篇文章主要介紹了SpringMVC自定義攔截器實(shí)現(xiàn)過(guò)程詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-05-05
Java二維數(shù)組實(shí)現(xiàn)數(shù)字拼圖效果
這篇文章主要為大家詳細(xì)介紹了Java二維數(shù)組實(shí)現(xiàn)數(shù)字拼圖效果,控制臺(tái)可以對(duì)空格進(jìn)行移動(dòng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-07-07
如何通過(guò)一個(gè)注解實(shí)現(xiàn)MyBatis字段加解密
用戶(hù)隱私很重要,因此很多公司開(kāi)始做數(shù)據(jù)加減密改造,下面這篇文章主要給大家介紹了關(guān)于如何通過(guò)一個(gè)注解實(shí)現(xiàn)MyBatis字段加解密的相關(guān)資料,需要的朋友可以參考下2022-02-02
java.lang.Instrument 代理Agent使用詳細(xì)介紹
這篇文章主要介紹了java.lang.Instrument 代理Agent使用詳細(xì)介紹的相關(guān)資料,附有實(shí)例代碼,幫助大家學(xué)習(xí)參考,需要的朋友可以參考下2016-11-11
在Android的應(yīng)用中實(shí)現(xiàn)網(wǎng)絡(luò)圖片異步加載的方法
這篇文章主要介紹了在Android的應(yīng)用中實(shí)現(xiàn)網(wǎng)絡(luò)圖片異步加載的方法,一定程度上有助于提高安卓程序的使用體驗(yàn),需要的朋友可以參考下2015-07-07
window?下?win10?jdk8安裝與環(huán)境變量的配置過(guò)程
這篇文章主要介紹了window?下?win10?jdk8安裝與環(huán)境變量的配置,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-08-08
強(qiáng)烈推薦 5 款好用的REST API工具(收藏)
市面上可用的 REST API 工具選項(xiàng)有很多,我們來(lái)看看其中一些開(kāi)發(fā)人員最喜歡的工具。本文通過(guò)圖文實(shí)例代碼相結(jié)合給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2020-12-12
探究MyBatis插件原理以及自定義插件實(shí)現(xiàn)
這篇文章主要介紹了探究MyBatis插件原理以及自定義插件實(shí)現(xiàn),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-07-07

