时间处理

前言

  之前我曾用C++的时间API来处理一些时间性的问题。比如下列场景 "获取整年的所有日期序列(即年月日小时分钟)","获取当前时间序列的前后六个小时时间序列","比较两个时间序列的先后"等。

  在C++中,这些场景需要写一定量的代码,而java中,通过使用GregorianCalendar类,能够很轻松的解决这些问题。

示例代码

 1 package test;
 2 
 3 import java.util.Calendar;
 4 import java.util.GregorianCalendar;
 5 
 6 public class Test {
 7 
 8     public static void main(String[] args)  {
 9         
10         // 打印 2014 年 12 月的每隔 6 小时的所有时间序列
11         // 月份从 0 开始计算(除了day和实际多少号一样之外,其他的参数如小时,分钟等都是从 0 开始算)。
12         // 因此 12 月对应的month参数就是11
13         GregorianCalendar curTime = new GregorianCalendar(2014, 11, 1);
14         
15         while (curTime.get(Calendar.MONTH) == 11) {
16             
17             // 打印当前时刻
18             System.out.println(curTime.getTime());
19             
20             // 可获取当前时刻的各种信息
21             // 比如: 年份 月份 日期 小时 分钟
22             /*
23                 int year = curTime.get(Calendar.YEAR);
24                 int month = curTime.get(curTime.MONTH);
25                 int day = curTime.get(Calendar.DAY_OF_MONTH);
26                 int minutes = curTime.get(curTime.MINUTE);
27             */
28 
29             // 往前移动6小时
30             curTime.add(Calendar.HOUR, 6);
31         }
32     }
33 }

执行结果

  

小结

  Java API还提供了大量的其他时间操作函数,这里不一一列举。

  一定要养成查阅API手册的好习惯。

原文地址:https://www.cnblogs.com/scut-fm/p/4094535.html