当前位置:   article > 正文

04-JAVA常用API-时间相关类_java格林时间api

java格林时间api

前言

全世界的时间有一个统一的计算标准.
世界标准时间:Greenwich Mean Time 格林尼治时间/格林威治时间 简称GMT

目前世界标准时间UTC已经替换为:原子钟

中国标准时间:世界标准时间+8小时

时间换算单位:一秒等于一千毫秒 一毫秒等于一千微秒 一微秒等于一千纳秒

Date时间类:

Date类是一个JDK写好的JavaBean类,用来描述时间,精确到毫秒.

利用空参构造创建的对象,默认表示系统当前时间.

利用有参构造创建的对象,表示指定的时间.

  1. public class demo1 {
  2. private long time;//当前时间的毫秒值
  3. public demo1() {//空参构造方法
  4. this.time = System.currentTimeMillis();
  5. }
  6. public demo1(long time) {//带参构造方法
  7. this.time = time;
  8. }
  9. public long getTime() {//get方法
  10. return time;
  11. }
  12. public void setTime(long time) {//set方法
  13. this.time = time;
  14. }
  15. }
  1. //1.创建对象表示一个时间
  2. Date d1 = new Date();
  3. System.out.println(d1);
  4. //2.创建对象表示一个指定的对象
  5. Date d2 = new Date(0L);
  6. System.out.println(d2);
  7. //3.settime修改时间
  8. d2.setTime(1000L);
  9. System.out.println(d2);
  10. //4.gettime获取当前时间的毫秒值
  11. long time = d2.getTime();
  12. System.out.println(time);

练习:

需求一:打印时间原点开始一年后的时间

  1. Date d1 = new Date(0L);
  2. //2.获取d1时间的毫秒值
  3. long time = d1.getTime();
  4. //3.在这个基础上我们加上一年的毫秒值
  5. time = time + 1000L * 60 * 60 * 24 * 365;
  6. //4.把计算之后的时间毫秒值,再设置回d1当中
  7. d1.setTime(time);
  8. System.out.println(d1);

需求二:定义任意两个Date对象,比较一下那个时间段在前,哪个时间在后
 

  1. Random r = new Random();
  2. Date d1 = new Date(Math.abs(r.nextInt()));
  3. Date d2 = new Date(Math.abs(r.nextInt()));
  4. System.out.println(d1);
  5. System.out.println(d2);
  6. long time1 = d1.getTime();
  7. long time2 = d2.getTime();
  8. if (time1 > time2) {
  9. System.out.println("time1>time2");
  10. } else if (time1 < time2) {
  11. System.out.println(time1 < time2);
  12. } else {
  13. System.out.println(time1 = time2);
  14. }

SimpleDateFormat类作用:

格式化:把时间变成我们喜欢的样式.

解析:把字符串表示的时间变成Date对象

构造方法说明
public SimpleDateFormat()构造一个SimpleDateFormat,使用默认格式
public SimpleDateFormat(String pattern)构造一个SimpleDateFormat,使用指定的格式
常用方法说明
public final String format(Date date)格式化(时间对象->字符串)
public Date parse(String source)解析(字符串->日期对象)

格式化的时间形式的常用的模式对应关系如下:

  1. //利用空参构造创建SimpleDateFormat对象,默认格式
  2. SimpleDateFormat sdf1 = new SimpleDateFormat();
  3. Date d1 = new Date();
  4. String str1 = sdf1.format(d1);
  5. System.out.println(str1);
  6. //利用空参构造创建SimpleDateFormat对象,指定格式
  7. SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年mm月dd日 HH:mm:ss");
  8. String str2 = sdf2.format(d1);
  9. System.out.println(str2);
  10. //定义一个字符串表示时间
  11. String str = "2023年00月09日 21:00:51";
  12. //利用空间构造创建SimpleDateFormat对象
  13. //细节:创建对象的格式跟字符串的格式要一致
  14. SimpleDateFormat sdf = new SimpleDateFormat("yyyy年mm月dd日 HH:mm:ss");
  15. Date date = sdf.parse(str);
  16. //3.打印结果
  17. System.out.println(date.getTime());
  1. String str = "2000-11-11";
  2. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  3. Date date = sdf.parse(str);
  4. SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日");
  5. String result = sdf1.format(date);
  6. System.out.println(result);

 

  1. //1.进行比较比较两个时间,比较下单时间和付款时间
  2. //转换成毫秒值
  3. String startTime = "2000-11-11 0:0:0";
  4. String endTime = "2000-11-12 0:0:0";
  5. String orderTime = "2000-11-11 0:0:0";
  6. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD");
  7. Date starttime = sdf.parse(startTime);
  8. Date endtime = sdf.parse(endTime);
  9. Date ordertime = sdf.parse(orderTime);
  10. long startstr = starttime.getTime();
  11. long endtstr = endtime.getTime();
  12. long orderstr = ordertime.getTime();
  13. if (orderstr>=startstr&&orderstr<=endtstr)
  14. {
  15. System.out.println("true");
  16. }else {
  17. System.out.println("false");
  18. }

Calender类的作用:

Calendar代表了系统当前的日历对象,可以单独修改,获取时间中的年月日

细节:Calendar是一个抽象类,不能直接创建对象.

获取calendar日历类对象的方法

方法名说明
public static Calendar getInstance()获取当前时间的日历对象

Calendar常用方法:

方法名说明
public final Date getTime()获取日期对象
public final setTime(Date fate)给日历设置日期对象
public long getTimeInMillis()拿到时间毫秒值
public void setTimeInMillion(long million)给日历设置时间毫秒值
public int get(int field)取日历中的某个字段信息
public void set(int field,int value)修改日历的某个字段信息
public void add(int field,int amount)为某个字段增加/减少指定的值
  1. //获取日历对象
  2. //calendar是一个抽象类,不能直接new,而是通过一个静态方法获取到子类对象.
  3. //底层原理:
  4. //根据系统不同时区来获取不同的日历对象,默认表示当前时间
  5. //会把时间中的纪元,年,月,日,时,分,秒等放到一个数组中
  6. //0:纪元
  7. //1:年
  8. //2.月
  9. //3:一年中第几周
  10. //4:一个月中的第几周
  11. //5:一个月的第几天
  12. //一共17个属性为0-16
  13. //Java为了防止我们忘记,把索引对应的数字定义成常量
  14. //细节2:
  15. //月份:范围是0_11 ,如果取出来的是1实际上是2月
  16. //星期:老外以星期日为第一天
  17. Calendar c = Calendar.getInstance();
  18. System.out.println(c);
  19. //2.修改日历代表的时间
  20. Date d= new Date(0L);
  21. c.setTime(d);
  22. System.out.println(c);
  23. //取日期中的某个字段信息
  24. int year = c.get(1);
  25. int month = c.get(Calendar.MONTH)+1;
  26. System.out.println(year);
  27. System.out.println(month);
  28. //修改日历的某个字段信息
  29. //为某个字段增加/减少指定的值
  30. }
  31. //查表法:表就是容器
  32. public static String getWeek(int dex){
  33. //定义一个数组,让汉字星期几 跟1-7产生对应关系
  34. String[] arr = {"7","1","2","3","4","5","6"};
  35. return arr[dex];
  36. }

JDK8新增时间相关类 

ZoneId时区:

方法名说明
static Set<string> getAvailableZoneIds()获取Java中支持的所有时区
static ZoneId systemDefault()获取系统默认时区
static ZoneId of(String zoneId)获取一个指定时区
  1. //1.获取所有时区名
  2. Set<String> zoneIds = ZoneId.getAvailableZoneIds();
  3. System.out.println(zoneIds.size());
  4. System.out.println(zoneIds);
  5. //2.获取系统默认时区
  6. ZoneId zoneId =ZoneId.systemDefault();
  7. System.out.println(zoneId);
  8. //3.获取一个指定时区
  9. ZoneId shanghai = ZoneId.of("Asia/Shanghai");
  10. System.out.println(shanghai);

Instant时间戳:

方法名说明
static Instant now()获取当前时间的instant对象(标准时间)
static Instant ofXxxx(long epochMilli)根据秒毫秒纳秒获取instant对象
ZonedDateTime atZone(ZoneId zone)指定时区
boolean isXxx(Instant otherInstant)判断系列的方法
Instant minusXxx(long millisToSubtract)减少时间系列的方法
Instant plusXxx(long millisToSubtract)增加时间系列的方法
  1. //1.获取当前时间的instant对象(标准时间)
  2. Instant now = Instant.now();
  3. System.out.println(now);
  4. //2.根据指定的毫秒值纳秒获取instant对象
  5. Instant instant1 = Instant.ofEpochMilli(0L);
  6. System.out.println(instant1);
  7. Instant instant2 = Instant.ofEpochSecond(1L);
  8. System.out.println(instant2);
  9. Instant instant3 = Instant.ofEpochSecond(1L, 1000000L);
  10. System.out.println(instant3);
  11. //3.指定时区
  12. ZonedDateTime time = Instant.now().atZone(ZoneId.of("Asia/Shanghai"));
  13. System.out.println(time);
  14. //4.判断系列的方法
  15. //ifbefore:判断调用者代表的时间是否在在参数表示时间的前面
  16. Instant instant4 = Instant.ofEpochMilli(0L);
  17. Instant instant5 = Instant.ofEpochMilli(10000L);
  18. boolean result = instant4.isBefore(instant5);
  19. //5.减少增加时间系列的方法
  20. Instant instant6 = Instant.ofEpochMilli(1111L);
  21. System.out.println(instant6);
  22. Instant instant7 = instant6.minusSeconds(1);
  23. System.out.println(instant7);

ZoneDateTime带时区的时间:

方法名说明
static ZonedDateTime now()获取当前时间ZonedDateTime对象
static ZonedDateTime ofXxxx()获取指定时间的ZonedDateTime对象
ZonedDateTime withXxx(time)修改时间系列的方法
ZonedDateTime minusXxx(time)减少时间系列的方法
ZonedDateTime plusXxx(time)增加时间系列的方法
  1. //1.获取当前时间的对象(带时区)
  2. ZonedDateTime now1 = ZonedDateTime.now();
  3. System.out.println(now1);
  4. //2.获取指定的时间对象(带时区)
  5. ZonedDateTime time2 = ZonedDateTime.of(2023, 10, 1, 11, 12, 12, 0, ZoneId.of("Asia/Shanghai"));
  6. System.out.println(time2);
  7. //3.通过instant+时区的方式指定获取时间对象
  8. Instant instant8 = Instant.ofEpochMilli(0L);
  9. ZoneId zoneid = ZoneId.of("Asia/Shanghai");
  10. ZonedDateTime time3 = ZonedDateTime.ofInstant(instant8, zoneid);
  11. System.out.println(time3);
  12. //3.withXxx修改时间系列的方法
  13. ZonedDateTime time4 = time3.withYear(2000);
  14. System.out.println(time3);
  15. //4.减少时间
  16. ZonedDateTime time5 = time3.minusYears(1);
  17. System.out.println(time5);
  18. //5.增加时间
  19. ZonedDateTime time6 = time5.plusYears(1);
  20. System.out.println(time5);

DateTimeFormatter用于时间的格式化和解析:

方法名说明
static DateTimeFormatter ofPattern(格式)获取格式对象
String format(时间对象)按照指定方式格式化
  1. //获取时间对象
  2. ZonedDateTime time = Instant.now().atZone(ZoneId.of("Asia/Shanghai"))
  3. ;
  4. //解析/格式化器
  5. DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss EE a");
  6. //格式化
  7. System.out.println(dtf1.format(time));

LocalDate年月日:

LocalTime时分秒:

LocalDateTime年月日时分秒:

方法名说明
static XXX now()获取当前时间的对象
static XXX of(...)获取指定时间的对象
get开头的方法获取日历中的年月日时分秒等信息
isBefore,isAfter比较两个localdate
with开头的修改时间系列的方法
minus开头的减少时间系列的方法
plus开头的增加时间系列的方法

方法名说明
public LocalDate toLocalDate()LocalDateTime转换成一个LocalDate对象
public LocalTime toLocalTime()LocalDateTime转换成一个LocalTime对象
  1. //1.获取当前时间的日历对象(包含 年月日)
  2. LocalDate nowDate = LocalDate.now();
  3. //System.out.println("今天的日期:" + nowDate);
  4. //2.获取指定的时间的日历对象
  5. LocalDate ldDate = LocalDate.of(2023, 1, 1);
  6. System.out.println("指定日期:" + ldDate);
  7. System.out.println("=============================");
  8. //3.get系列方法获取日历中的每一个属性值//获取年
  9. int year = ldDate.getYear();
  10. System.out.println("year: " + year);
  11. //获取月//方式一:
  12. Month m = ldDate.getMonth();
  13. System.out.println(m);
  14. System.out.println(m.getValue());
  15. //方式二:
  16. int month = ldDate.getMonthValue();
  17. System.out.println("month: " + month);
  18. //获取日
  19. int day = ldDate.getDayOfMonth();
  20. System.out.println("day:" + day);
  21. //获取一年的第几天
  22. int dayofYear = ldDate.getDayOfYear();
  23. System.out.println("dayOfYear:" + dayofYear);
  24. //获取星期
  25. DayOfWeek dayOfWeek = ldDate.getDayOfWeek();
  26. System.out.println(dayOfWeek);
  27. System.out.println(dayOfWeek.getValue());
  28. //is开头的方法表示判断
  29. System.out.println(ldDate.isBefore(ldDate));
  30. System.out.println(ldDate.isAfter(ldDate));
  31. //with开头的方法表示修改,只能修改年月日
  32. LocalDate withLocalDate = ldDate.withYear(2000);
  33. System.out.println(withLocalDate);
  34. //minus开头的方法表示减少,只能减少年月日
  35. LocalDate minusLocalDate = ldDate.minusYears(1);
  36. System.out.println(minusLocalDate);
  37. //plus开头的方法表示增加,只能增加年月日
  38. LocalDate plusLocalDate = ldDate.plusDays(1);
  39. System.out.println(plusLocalDate);
  40. //-------------
  41. // 判断今天是否是你的生日
  42. LocalDate birDate = LocalDate.of(2000, 1, 1);
  43. LocalDate nowDate1 = LocalDate.now();
  44. MonthDay birMd = MonthDay.of(birDate.getMonthValue(), birDate.getDayOfMonth());
  45. MonthDay nowMd = MonthDay.from(nowDate1);
  46. System.out.println("今天是你的生日吗? " + birMd.equals(nowMd));//今天是你的生日吗?
  47. // 获取本地时间的日历对象。(包含 时分秒)
  48. LocalTime nowTime = LocalTime.now();
  49. System.out.println("今天的时间:" + nowTime);
  50. int hour = nowTime.getHour();//时
  51. System.out.println("hour: " + hour);
  52. int minute = nowTime.getMinute();//分
  53. System.out.println("minute: " + minute);
  54. int second = nowTime.getSecond();//秒
  55. System.out.println("second:" + second);
  56. int nano = nowTime.getNano();//纳秒
  57. System.out.println("nano:" + nano);
  58. System.out.println("------------------------------------");
  59. System.out.println(LocalTime.of(8, 20));//时分
  60. System.out.println(LocalTime.of(8, 20, 30));//时分秒
  61. System.out.println(LocalTime.of(8, 20, 30, 150));//时分秒纳秒
  62. LocalTime mTime = LocalTime.of(8, 20, 30, 150);
  63. //is系列的方法
  64. System.out.println(nowTime.isBefore(mTime));
  65. System.out.println(nowTime.isAfter(mTime));
  66. //with系列的方法,只能修改时、分、秒
  67. System.out.println(nowTime.withHour(10));
  68. //plus系列的方法,只能修改时、分、秒
  69. System.out.println(nowTime.plusHours(10));
  70. // 当前时间的的日历对象(包含年月日时分秒)
  71. LocalDateTime nowDateTime = LocalDateTime.now();
  72. System.out.println("今天是:" + nowDateTime);//今天是:
  73. System.out.println(nowDateTime.getYear());//年
  74. System.out.println(nowDateTime.getMonthValue());//月
  75. System.out.println(nowDateTime.getDayOfMonth());//日
  76. System.out.println(nowDateTime.getHour());//时
  77. System.out.println(nowDateTime.getMinute());//分
  78. System.out.println(nowDateTime.getSecond());//秒
  79. System.out.println(nowDateTime.getNano());//纳秒
  80. // 日:当年的第几天
  81. System.out.println("dayofYear:" + nowDateTime.getDayOfYear());
  82. //星期
  83. System.out.println(nowDateTime.getDayOfWeek());
  84. System.out.println(nowDateTime.getDayOfWeek().getValue());
  85. //月份
  86. System.out.println(nowDateTime.getMonth());
  87. System.out.println(nowDateTime.getMonth().getValue());
  88. LocalDate ld = nowDateTime.toLocalDate();
  89. System.out.println(ld);
  90. LocalTime lt = nowDateTime.toLocalTime();
  91. System.out.println(lt.getHour());
  92. System.out.println(lt.getMinute());
  93. System.out.println(lt.getSecond());

Duration时间间隔(秒,纳秒):

用于计算两个时间间隔(秒,纳秒)

  1. // 本地日期时间对象。
  2. LocalDateTime today = LocalDateTime.now();
  3. System.out.println(today);
  4. // 出生的日期时间对象
  5. LocalDateTime birthDate = LocalDateTime.of(2000, 1, 1, 0, 0, 0);
  6. System.out.println(birthDate);
  7. Duration duration = Duration.between(birthDate, today);//第二个参数减第一个参数
  8. System.out.println("相差的时间间隔对象:" + duration);
  9. System.out.println("============================================");
  10. System.out.println(duration.toDays());//两个时间差的天数
  11. System.out.println(duration.toHours());//两个时间差的小时数
  12. System.out.println(duration.toMinutes());//两个时间差的分钟数
  13. System.out.println(duration.toMillis());//两个时间差的毫秒数
  14. System.out.println(duration.toNanos());//两个时间差的纳秒数

Period时间间隔(年月日):

用于计算两个日期间隔(年月日)

  1. // 当前本地 年月日
  2. LocalDate today = LocalDate.now();
  3. System.out.println(today);
  4. // 生日的 年月日
  5. LocalDate birthDate = LocalDate.of(2000, 1, 1);
  6. System.out.println(birthDate);
  7. Period period = Period.between(birthDate, today);//第二个参数减第一个参数
  8. System.out.println("相差的时间间隔对象:" + period);
  9. System.out.println(period.getYears());
  10. System.out.println(period.getMonths());
  11. System.out.println(period.getDays());
  12. System.out.println(period.toTotalMonths());

ChronoUnit时间间隔(所有单位):

用于计算两个日期间隔

  1. // 当前时间
  2. LocalDateTime today = LocalDateTime.now();
  3. System.out.println(today);
  4. // 生日时间
  5. LocalDateTime birthDate = LocalDateTime.of(2000, 1, 1,
  6. 0, 0, 0);
  7. System.out.println(birthDate);
  8. System.out.println("相差的年数:" + ChronoUnit.YEARS.between(birthDate, today));
  9. System.out.println("相差的月数:" + ChronoUnit.MONTHS.between(birthDate, today));
  10. System.out.println("相差的周数:" + ChronoUnit.WEEKS.between(birthDate, today));
  11. System.out.println("相差的天数:" + ChronoUnit.DAYS.between(birthDate, today));
  12. System.out.println("相差的时数:" + ChronoUnit.HOURS.between(birthDate, today));
  13. System.out.println("相差的分数:" + ChronoUnit.MINUTES.between(birthDate, today));
  14. System.out.println("相差的秒数:" + ChronoUnit.SECONDS.between(birthDate, today));
  15. System.out.println("相差的毫秒数:" + ChronoUnit.MILLIS.between(birthDate, today));
  16. System.out.println("相差的微秒数:" + ChronoUnit.MICROS.between(birthDate, today));
  17. System.out.println("相差的纳秒数:" + ChronoUnit.NANOS.between(birthDate, today));
  18. System.out.println("相差的半天数:" + ChronoUnit.HALF_DAYS.between(birthDate, today));
  19. System.out.println("相差的十年数:" + ChronoUnit.DECADES.between(birthDate, today));
  20. System.out.println("相差的世纪(百年)数:" + ChronoUnit.CENTURIES.between(birthDate, today));
  21. System.out.println("相差的千年数:" + ChronoUnit.MILLENNIA.between(birthDate, today));
  22. System.out.println("相差的纪元数:" + ChronoUnit.ERAS.between(birthDate, today));

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/49164
推荐阅读
相关标签
  

闽ICP备14008679号