java 如何创建时间
创建当前时间
使用 java.util.Date 类可以获取当前时间。Date 对象默认表示当前的日期和时间。
Date currentDate = new Date();
System.out.println(currentDate);
使用 Calendar 类创建时间
java.util.Calendar 类提供了更灵活的时间操作方式。可以通过 Calendar 实例设置特定的日期和时间。
Calendar calendar = Calendar.getInstance();
calendar.set(2023, Calendar.JANUARY, 1, 12, 30, 0);
Date specificDate = calendar.getTime();
System.out.println(specificDate);
使用 LocalDateTime(Java 8+)
Java 8 引入了 java.time 包,其中 LocalDateTime 类用于表示不带时区的日期和时间。可以通过静态方法创建特定时间。
LocalDateTime currentTime = LocalDateTime.now();
System.out.println(currentTime);
LocalDateTime specificTime = LocalDateTime.of(2023, 1, 1, 12, 30, 0);
System.out.println(specificTime);
使用 SimpleDateFormat 格式化时间
SimpleDateFormat 类可以将 Date 对象格式化为特定的字符串表示形式,便于显示或存储。
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
使用 DateTimeFormatter(Java 8+)
Java 8 的 DateTimeFormatter 类用于格式化 LocalDateTime 对象,提供更现代的日期时间处理方式。
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = now.format(formatter);
System.out.println(formattedDateTime);
从字符串解析时间
可以通过 SimpleDateFormat 或 DateTimeFormatter 将字符串解析为时间对象。
String dateString = "2023-01-01 12:30:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date parsedDate = sdf.parse(dateString);
System.out.println(parsedDate);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parsedLocalDateTime = LocalDateTime.parse(dateString, dtf);
System.out.println(parsedLocalDateTime);
使用时间戳创建时间
可以通过时间戳(毫秒数)创建 Date 或 Instant 对象。
long timestamp = System.currentTimeMillis();
Date dateFromTimestamp = new Date(timestamp);
System.out.println(dateFromTimestamp);
Instant instant = Instant.ofEpochMilli(timestamp);
System.out.println(instant);
使用 ZonedDateTime 处理时区
ZonedDateTime 类用于处理带时区的日期和时间,适用于需要时区信息的场景。

ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("America/New_York"));
System.out.println(zonedDateTime);






