友友们,互三咯~
在 Java 开发领域,时间处理是一项极为常见且关键的需求。无论是记录用户的操作时间,还是实现定时任务等功能,都离不开对时间 API 的灵活运用。本文围绕 JDK7 与 JDK8 中的时间处理类,结合学习内容,详细梳理Date、SimpleDateFormat、Calendar以及 JDK8 全新时间类的使用与演进,助力开发者掌握 Java 时间处理的核心要点。
Date类位于java.util包下,是 JDK7 中用于表示特定瞬间的时间类,其精度可达到毫秒级别。它的出现,为 Java 处理时间提供了基础能力。
创建Date对象的方式较为简单,通过无参构造方法可以直接获取当前系统时间:
import java.util.Date;
public class DateDemo {
public static void main(String[] args) {
Date now = new Date();
System.out.println("当前系统时间:" + now);
}
}
上述代码的输出结果类似Thu Jul 23 10:00:00 CST 2025,能够直观地呈现当下的时间信息。
尽管Date类能够获取和表示时间,但在实际开发过程中,它的短板逐渐显现出来:
SimpleDateFormat是java.text包下的一个类,它专门用于对Date类进行格式化(将Date对象转换为指定格式的字符串)和解析(将符合格式的字符串转换回Date对象)操作。通过自定义的模式字符串,SimpleDateFormat能够灵活地控制时间的展示样式。
掌握以下这些模式符号,就能根据需求定制出所需的时间格式:
将Date对象转换为 “yyyy - MM - dd HH:mm:ss” 格式的字符串:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatParseDemo {
public static void main(String[] args) {
String timeStr = "2025-07-23 10:20:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = sdf.parse(timeStr);
System.out.println("解析后的 Date 对象:" + date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
运行上述代码后,时间会按照设定的格式输出,例如2025-07-23 10:15:30,大大提升了时间的可读性。
将符合格式的字符串转换回Date对象:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatParseDemo {
public static void main(String[] args) {
String timeStr = "2025-07-23 10:20:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = sdf.parse(timeStr);
System.out.println("解析后的 Date 对象:" + date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
需要注意的是,在进行解析操作时,字符串的格式必须和模式严格匹配,否则会抛出ParseException异常,因此要做好异常处理工作。
Calendar是java.util包下的一个抽象类,与Date类相比,它提供了更为丰富的时间操作方法,能够方便地获取、设置时间字段(如年、月、日、时等),还支持对时间进行加减运算。
由于Calendar是抽象类,不能直接通过new关键字来创建实例,而是需要通过getInstance方法来获取:
import java.util.Calendar;
public class CalendarDemo {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
}
}
该方法返回的是GregorianCalendar实例(即公历),能够适配大部分的使用场景。
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1; // 月份从 0 开始,需要加 1
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY); // 采用24小时制
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
System.out.println("当前时间:" + year + "年" + month + "月" + day + "日 " + hour + ":" + minute + ":" + second);
calendar.set(Calendar.YEAR, 2026);
calendar.set(Calendar.MONTH, Calendar.JANUARY); // 直接使用常量,更具语义性
calendar.set(Calendar.DAY_OF_MONTH, 1);
// 也可以一次性设置多个字段
calendar.set(2026, Calendar.FEBRUARY, 14, 18, 30, 0);
calendar.add(Calendar.DAY_OF_MONTH, 7); // 将当前时间加 7 天
calendar.add(Calendar.HOUR, -3); // 将当前时间减 3 小时
这些操作使得时间调整变得灵活高效,能够轻松实现诸如计算 “一周后的时间”“三小时前的时间” 等需求。
通过这种转换方式,能够在两种时间表示形式之间进行切换,以适配不同 API 的需求。
JDK8 引入了全新的时间 API(位于java.time包下),解决了 JDK7 时间类存在的诸多痛点,如线程不安全、设计复杂等问题,以下是其中的核心类介绍:
import java.time.LocalDate;
public class LocalDateDemo {
public static void main(String[] args) {
LocalDate nowDate = LocalDate.now();
System.out.println("当前日期:" + nowDate);
LocalDate 指定日期 = LocalDate.of(2025, 7, 23);
int year = 指定日期.getYear();
int month = 指定日期.getMonthValue();
int day = 指定日期.getDayOfMonth();
LocalDate 加 5 天 = 指定日期.plusDays(5);
LocalDate 减 3 月 = 指定日期.minusMonths(3);
}
}
import java.time.LocalDateTime;
public class LocalDateTimeDemo {
public static void main(String[] args) {
LocalDateTime nowDateTime = LocalDateTime.now();
LocalDateTime 指定时间 = LocalDateTime.of(2025, 7, 23, 10, 30, 0);
// 支持丰富的时间调整,如调整到下一个周一、设置秒数等
LocalDateTime 下周一 = nowDateTime.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
}
}
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class ZonedDateTimeDemo {
public static void main(String[] args) {
ZonedDateTime 上海时间 = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
ZonedDateTime 纽约时间 = ZonedDateTime.now(ZoneId.of("America/New_York"));
// 时区转换
ZonedDateTime 上海转纽约 = 上海时间.withZoneSameInstant(ZoneId.of("America/New_York"));
}
}
DateTimeFormatter是 JDK8 中用于格式化和解析时间的类,它是线程安全的,可以替代SimpleDateFormat。示例如下:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeFormatterDemo {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatStr = now.format(formatter);
System.out.println("格式化后:" + formatStr);
LocalDateTime parseTime = LocalDateTime.parse("2025-07-23 10:45:00", formatter);
}
}
从 JDK7 的Date、SimpleDateFormat、Calendar,到 JDK8 的全新时间 API,Java 的时间处理能力在不断演进。在学习过程中,要理解不同类的适用场景,掌握核心方法,在实际开发中根据需求灵活选择合适的时间类。JDK8 的时间类代表了未来的发展趋势,值得深入学习和运用,从而让时间处理变得更加高效、简洁。随着对 Java 时间 API 的掌握愈发熟练,在处理日期时间相关需求时,也能更加得心应手,为构建健壮、易维护的 Java 程序奠定坚实的基础。