Java 日期、字符串与国际化:全面解析
1. 日期与时间处理
在 Java 中,日期和时间的处理需要使用特定的类和方法。例如,下面的代码展示了如何创建一个带时区的日期时间对象:
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.Month;
public class DateTimeExample {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2016, Month.MARCH, 13);
LocalTime time = LocalTime.of(2, 30);
ZoneId zone = ZoneId.of("US/Eastern");
ZonedDateTime dateTime = ZonedDateTime.of(date, time, zone);
System.out.println(dateTime); // 2016–03–13T03:30–04:00[US/Eastern]
}
}
Java 会智能地处理时区和夏令时的问题。在上述例子中,由于特定日期和时区的原因, 2:30 a.m.
并不存在,Java 会自动切换到合适的 GMT 偏移量。