Java Time Zone Handling and Date-Time Operations

Java provides robust time zone managemant through the java.time API. China historically used five distinct time zones:

  • Asia/Harbin: GMT+8:30 (Changbai Time Zone)
  • Asia/Shanghai: GMT+8 (Standard Time Zone)
  • Asia/Chongqing: GMT+7 (Longshu Time Zone)
  • Asia/Urumqi: GMT+6 (Tibetan Time Zone)
  • Asia/Kashgar: GMT+5:30 (Kunlun Time Zone)

Retrieving Time Zones

<code>
// Preferred: Specific time zone
ZoneId targetZone = TimeZone.getTimeZone("Asia/Shanghai").toZoneId();

// Alternative: System default (not recommended for consistency)
ZoneId systemZone = ZoneId.systemDefault();
</code>

Curent Date and Time

<code>
ZoneId chinaZone = TimeZone.getTimeZone("Asia/Shanghai").toZoneId();
LocalDate currentDate = LocalDate.now(chinaZone);
LocalDateTime currentDateTime = LocalDateTime.now(chinaZone);
</code>

Formatted Standard Time

<code>
ZoneId chinaZone = TimeZone.getTimeZone("Asia/Shanghai").toZoneId();
String formattedDate = DateTimeFormatter.ofPattern("yyyy-MM-dd")
                          .format(LocalDate.now(chinaZone));
String formattedDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                             .format(LocalDateTime.now(chinaZone));
</code>

Milliseconds to DateTime Conversion

<code>
ZoneId zone = TimeZone.getTimeZone("Asia/Shanghai").toZoneId();
// Recommended approach
LocalDateTime converted = Instant.ofEpochMilli(1777280940692L)
                           .atZone(zone)
                           .toLocalDateTime();

// Alternative method
LocalDateTime alternateConversion = LocalDateTime.ofInstant(
    Instant.ofEpochMilli(1777280940692L), zone
);
</code>

Month Boundary Calculations

<code>
YearMonth currentMonth = YearMonth.now();
String monthStart = currentMonth.atDay(1).format(
    DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " 00:00:00";

String monthEnd = currentMonth.atEndOfMonth().format(
    DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " 23:59:59";
</code>

Year Range Calculation

<code>
LocalDate today = LocalDate.now();
String yearStart = today.minusYears(1).plusDays(1)
                 .format(DateTimeFormatter.ISO_DATE) + " 00:00:00";
String yearEnd = today.format(DateTimeFormatter.ISO_DATE) + " 23:59:59";
</code>

Date Conversion Techniquse

<code>
// Legacy Date conversion
ZoneId zone = TimeZone.getTimeZone("Asia/Shanghai").toZoneId();
LocalDateTime customTime = LocalDateTime.parse("2022-10-24 23:59:59", 
    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
Date legacyDate = Date.from(customTime.atZone(zone).toInstant());
</code>

Tags: java timezone LocalDate LocalDateTime DateTimeFormatter

Posted on Sat, 12 Sep 2026 16:30:34 +0000 by sdaniels