java时间处理详细教程与代码案例
一、基础概念
1. 时间与日期基本概念
时区(timezone):地球被划分为24个时区,每个时区相差1小时。java中使用zoneid
表示时区。
时间戳(timestamp):从1970年1月1日00:00:00 gmt开始的毫秒数,java中用instant
类表示。
本地日期时间(localdatetime):不包含时区信息的日期和时间,java中用localdatetime
类表示。
时间格式(datetime format):用于日期时间的显示和解析,如"yyyy-mm-dd hh:mm:ss"。
二、传统日期时间api
1. java.util.date类
// 创建当前时间的date对象 date now = new date(); system.out.println("当前时间: " + now); // 创建指定时间的date对象 date specificdate = new date(121, 6, 15); // 2021年7月15日(年份从1900开始,月份从0开始) system.out.println("指定时间: " + specificdate); // 获取时间戳 long timestamp = now.gettime(); system.out.println("时间戳: " + timestamp); // 比较两个date对象 system.out.println("比较结果: " + now.compareto(specificdate));
2. java.util.calendar类
// 获取calendar实例 calendar calendar = calendar.getinstance(); system.out.println("当前时间: " + calendar.gettime()); // 设置特定日期 calendar.set(2023, calendar.july, 31, 14, 30, 0); system.out.println("设置后的时间: " + calendar.gettime()); // 获取特定字段 int year = calendar.get(calendar.year); int month = calendar.get(calendar.month) + 1; // 月份从0开始 int day = calendar.get(calendar.day_of_month); system.out.printf("%d年%d月%d日\n", year, month, day); // 日期计算 calendar.add(calendar.day_of_month, 5); // 加5天 system.out.println("加5天后的时间: " + calendar.gettime());
3. java.text.simpledateformat
// 创建simpledateformat实例 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(); } // 线程安全的格式化方式 dateformat df = new simpledateformat("yyyy-mm-dd"); string result = df.format(new date());
三、java 8新日期时间api
1. java.time包概述
java 8引入了全新的日期时间api,位于java.time
包中,主要类包括:
instant
- 时间戳localdate
- 不含时间的日期localtime
- 不含日期的时间localdatetime
- 不含时区的日期时间zoneddatetime
- 带时区的日期时间period
- 日期区间duration
- 时间区间
2. 主要类介绍
localdate
// 获取当前日期 localdate today = localdate.now(); system.out.println("当前日期: " + today); // 创建特定日期 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
// 获取当前时间 localtime now = localtime.now(); system.out.println("当前时间: " + now); // 创建特定时间 localtime specifictime = localtime.of(14, 30, 45); system.out.println("指定时间: " + specifictime); // 从字符串解析 localtime parsedtime = localtime.parse("15:30:00"); system.out.println("解析的时间: " + parsedtime); // 获取时间字段 system.out.println("时: " + now.gethour()); system.out.println("分: " + now.getminute()); system.out.println("秒: " + now.getsecond());
localdatetime
// 获取当前日期时间 localdatetime now = localdatetime.now(); system.out.println("当前日期时间: " + now); // 创建特定日期时间 localdatetime specificdatetime = localdatetime.of(2023, month.july, 31, 14, 30, 45); system.out.println("指定日期时间: " + specificdatetime); // 从localdate和localtime组合 localdatetime combineddatetime = localdatetime.of(localdate.now(), localtime.now()); system.out.println("组合的日期时间: " + combineddatetime); // 获取字段 system.out.println("年: " + now.getyear()); system.out.println("时: " + now.gethour());
zoneddatetime
// 获取当前时区的日期时间 zoneddatetime now = zoneddatetime.now(); system.out.println("当前时区日期时间: " + now); // 创建特定时区的日期时间 zoneid tokyozone = zoneid.of("asia/tokyo"); zoneddatetime tokyotime = zoneddatetime.now(tokyozone); system.out.println("东京时间: " + tokyotime); // 时区转换 zoneddatetime newyorktime = now.withzonesameinstant(zoneid.of("america/new_york")); system.out.println("纽约时间: " + newyorktime);
instant
// 获取当前时间戳 instant now = instant.now(); system.out.println("当前时间戳: " + now); // 从毫秒数创建 instant specificinstant = instant.ofepochmilli(1690800000000l); system.out.println("指定时间戳: " + specificinstant); // 转换为localdatetime localdatetime localdatetime = localdatetime.ofinstant(now, zoneid.systemdefault()); system.out.println("转换为本地日期时间: " + localdatetime);
3. 日期时间操作
// 日期时间计算 localdatetime now = localdatetime.now(); system.out.println("当前时间: " + now); // 加3天 localdatetime plusdays = now.plusdays(3); system.out.println("加3天: " + plusdays); // 减2小时 localdatetime minushours = now.minushours(2); system.out.println("减2小时: " + minushours); // 加6个月 localdatetime plusmonths = now.plusmonths(6); system.out.println("加6个月: " + 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小时: " + result2);
4. 格式化与解析
// 创建datetimeformatter datetimeformatter formatter = datetimeformatter.ofpattern("yyyy-mm-dd hh:mm:ss"); // 格式化 string formatteddatetime = localdatetime.now().format(formatter); system.out.println("格式化后的日期时间: " + formatteddatetime); // 解析 localdatetime parseddatetime = localdatetime.parse("2023-07-31 15:30:00", formatter); system.out.println("解析后的日期时间: " + parseddatetime); // 预定义的格式 datetimeformatter isoformatter = datetimeformatter.iso_local_date_time; string isoformatted = localdatetime.now().format(isoformatter); system.out.println("iso格式: " + isoformatted);
四、时间转换与计算
1. 新旧api转换
// date转instant date date = new date(); instant instant = date.toinstant(); system.out.println("date转instant: " + instant); // instant转date date newdate = date.from(instant); system.out.println("instant转date: " + newdate); // calendar转zoneddatetime calendar calendar = calendar.getinstance(); zoneddatetime zoneddatetime = zoneddatetime.ofinstant(calendar.toinstant(), calendar.gettimezone().tozoneid()); system.out.println("calendar转zoneddatetime: " + zoneddatetime); // zoneddatetime转calendar calendar newcalendar = calendar.getinstance(); newcalendar.clear(); newcalendar.settime(date.from(zoneddatetime.toinstant())); system.out.println("zoneddatetime转calendar: " + newcalendar.gettime());
2. 时区处理
// 获取所有可用时区 set<string> allzones = zoneid.getavailablezoneids(); system.out.println("所有时区数量: " + allzones.size()); // 时区转换 zoneddatetime now = zoneddatetime.now(); system.out.println("当前时区时间: " + now); zoneddatetime londontime = now.withzonesameinstant(zoneid.of("europe/london")); system.out.println("伦敦时间: " + londontime); zoneddatetime newyorktime = now.withzonesameinstant(zoneid.of("america/new_york")); system.out.println("纽约时间: " + newyorktime); // 夏令时检查 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("伦敦夏令时偏移: " + summertime.getoffset()); system.out.println("伦敦冬令时偏移: " + wintertime.getoffset());
3. 时间差计算
// 计算两个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个月%d天\n", period.getyears(), period.getmonths(), period.getdays()); // 计算两个localtime之间的duration localtime starttime = localtime.of(8, 30); localtime endtime = localtime.of(17, 45); duration duration = duration.between(starttime, endtime); system.out.println("时间差: " + duration.tohours() + "小时" + (duration.tominutes() % 60) + "分钟"); // 使用chronounit long daysbetween = chronounit.days.between(startdate, enddate); system.out.println("相差天数: " + daysbetween); long hoursbetween = chronounit.hours.between(starttime, endtime); system.out.println("相差小时数: " + hoursbetween);
五、高级应用
1. 工作日计算
// 计算工作日(排除周末) 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月工作日天数: " + workingdays); // 使用temporaladjusters localdate nextworkingday = localdate.now().with(temporaladjusters.nextorsame(dayofweek.monday)); system.out.println("下一个工作日: " + nextworkingday);
2. 定时任务与时间处理
// 使用timer/timertask timer timer = new timer(); timer.schedule(new timertask() { @override public void run() { system.out.println("定时任务执行: " + localtime.now()); } }, 0, 1000); // 立即开始,每隔1秒执行一次 // 5秒后取消定时任务 try { thread.sleep(5000); } catch (interruptedexception e) { e.printstacktrace(); } timer.cancel(); // 使用scheduledexecutorservice scheduledexecutorservice executor = executors.newscheduledthreadpool(1); executor.scheduleatfixedrate( () -> system.out.println("调度任务执行: " + localtime.now()), 0, 1, timeunit.seconds); // 5秒后关闭 try { thread.sleep(5000); } catch (interruptedexception e) { e.printstacktrace(); } executor.shutdown();
3. 数据库时间处理
// jdbc与java.time类型映射 // 假设有preparedstatement ps和resultset rs // 写入数据库 localdatetime now = localdatetime.now(); ps.setobject(1, now); // 直接使用setobject // 从数据库读取 localdatetime dbdatetime = rs.getobject("date_column", localdatetime.class); // jpa/hibernate实体类中的时间字段 /* @entity public class event { @id private long id; @column private localdatetime eventtime; @column private localdate eventdate; // getters and setters } */
4. 序列化与反序列化
// json中的时间处理(使用jackson) objectmapper mapper = new objectmapper(); // 注册javatimemodule以支持java.time类型 mapper.registermodule(new javatimemodule()); // 禁用时间戳格式 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("解析后的时间: " + parsedevent.geteventtime());
六、最佳实践与常见问题
1. 线程安全最佳实践
// 传统api不是线程安全的 simpledateformat unsafeformat = new simpledateformat("yyyy-mm-dd"); // 解决方案1:每次创建新实例 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是线程安全的,可以共享实例 datetimeformatter safeformatter = datetimeformatter.ofpattern("yyyy-mm-dd");
2. 性能优化建议
// 重用datetimeformatter实例 private static final datetimeformatter formatter = datetimeformatter.ofpattern("yyyy-mm-dd hh:mm:ss"); // 批量格式化日期时间 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. 常见陷阱与解决方案
// 陷阱1:月份从0开始(传统api) calendar calendar = calendar.getinstance(); calendar.set(2023, 6, 31); // 实际上是7月31日 system.out.println("月份陷阱: " + calendar.gettime()); // 解决方案:使用常量 calendar.set(2023, calendar.july, 31); // 陷阱2:simpledateformat的线程安全问题 // 解决方案:如前面所述,使用threadlocal或每次创建新实例 // 陷阱3:时区忽略 localdatetime localdatetime = localdatetime.now(); zoneddatetime zoneddatetime = zoneddatetime.now(); system.out.println("localdatetime: " + localdatetime); system.out.println("zoneddatetime: " + zoneddatetime); // 解决方案:明确使用时区 zoneddatetime correctzoned = localdatetime.atzone(zoneid.systemdefault());
4. 国际化注意事项
// 本地化日期格式 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("美国格式: " + now.format(usformatter)); system.out.println("中国格式: " + now.format(chinaformatter)); // 本地化星期和月份名称 string dayname = now.getdayofweek().getdisplayname(textstyle.full, chinalocale); string monthname = now.getmonth().getdisplayname(textstyle.full, chinalocale); system.out.println("中文星期: " + dayname); system.out.println("中文月份: " + monthname);
七、扩展学习
1. joda-time库简介
// joda-time的基本使用(如果项目中已添加依赖) /* <dependency> <groupid>joda-time</groupid> <artifactid>joda-time</artifactid> <version>2.10.10</version> </dependency> */ // 创建datetime实例 org.joda.time.datetime jodadatetime = new org.joda.time.datetime(); system.out.println("joda-time当前时间: " + jodadatetime); // 日期计算 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项目
// threeten-extra提供了额外的日期时间类 /* <dependency> <groupid>org.threeten</groupid> <artifactid>threeten-extra</artifactid> <version>1.7.0</version> </dependency> */ // 使用interval类 org.threeten.extra.interval interval = org.threeten.extra.interval.of( instant.now(), instant.now().plusseconds(3600)); system.out.println("interval时长: " + interval.toduration().getseconds() + "秒"); // 使用yearquarter类 org.threeten.extra.yearquarter yearquarter = org.threeten.extra.yearquarter.now(); system.out.println("当前季度: " + yearquarter);
八、实战项目
1. 开发一个时间工具类
public class datetimeutils { private static final datetimeformatter default_formatter = datetimeformatter.ofpattern("yyyy-mm-dd hh:mm:ss"); // 获取当前时间字符串 public static string now() { return localdatetime.now().format(default_formatter); } // 计算两个日期之间的工作日 public static long calculateworkingdays(localdate start, localdate end) { return start.datesuntil(end) .filter(date -> date.getdayofweek() != dayofweek.saturday && date.getdayofweek() != dayofweek.sunday) .count(); } // 时区转换 public static zoneddatetime converttimezone(zoneddatetime datetime, string zoneid) { return datetime.withzonesameinstant(zoneid.of(zoneid)); } // 测试工具类 public static void main(string[] args) { system.out.println("当前时间: " + datetimeutils.now()); localdate start = localdate.of(2023, 7, 1); localdate end = localdate.of(2023, 7, 31); system.out.println("工作日天数: " + calculateworkingdays(start, end)); zoneddatetime now = zoneddatetime.now(); system.out.println("纽约时间: " + converttimezone(now, "america/new_york")); } }
2. 实现一个工作日计算器
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年国庆假期 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年国庆假期期间的工作日天数: " + workingdays); } }
3. 构建一个跨时区会议系统的时间处理模块
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在纽约安排会议时间为2023-07-31 14:00 localdatetime meetingtime = localdatetime.of(2023, 7, 31, 14, 0); map<string, zoneddatetime> schedule = scheduler.schedulemeeting("alice", meetingtime); // 打印各参与者的本地时间 schedule.foreach((name, time) -> { system.out.printf("%s的本地会议时间: %s %s\n", name, time.format(datetimeformatter.ofpattern("yyyy-mm-dd hh:mm")), time.getzone()); }); } }
这个完整的java时间处理教程涵盖了从基础概念到高级应用的各个方面,并提供了丰富的代码示例。您可以根据自己的需求选择相应的部分进行学习和实践。
到此这篇关于java时间处理详细教程与最佳实践案例的文章就介绍到这了,更多相关java时间处理内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论