Java 日期和时间
Java提供了在java.util包中可用的 Date 类,它封装了当前的日期和时间。
Date类支持如下表所示的两个构造方法。
| 序号 | 构造函数及其说明 | 
|---|---|
| 1 | 日期() 此构造函数将对象初始化为当前日期和时间。 | 
| 2 | 日期(long毫秒) 此构造函数接受一个参数,该参数等于自1970年1月1日午夜以来经过的毫秒数。 | 
以下是日期类的方法。
| 序号 | 方法与描述 | 
|---|---|
| 1 | boolean after(Date date) 如果调用的Date对象包含的日期晚于指定的日期,则返回true; 否则返回false。 | 
| 2 | boolean before(Date date) 如果调用的Date对象包含的日期早于指定的日期,则返回true; 否则返回false。 | 
| 3 | Object clone( ) 复制调用的Date对象。 | 
| 4 | int compareTo(Date date) 将调用对象的值与date进行比较。 如果值相等,则返回0。 如果调用对象早于date,则返回负值。 如果调用对象晚于date,则返回正值。 | 
| 5 | int compareTo(Object obj) 如果obj属于Date类,则与compareTo(Date)的操作相同。 否则,抛出ClassCastException异常。 | 
| 6 | boolean equals(Object date) 如果调用的Date对象包含与指定的日期相同的时间和日期,则返回true; 否则返回false。 | 
| 7 | long getTime( ) 返回自1970年1月1日以来经过的毫秒数。 | 
| 8 | int hashCode( ) 返回调用对象的哈希码。 | 
| 9 | void setTime(long time) 设置时间和日期,由time指定,其表示从1970年1月1日午夜以来的经过的毫秒数。 | 
| 10 | String toString( ) 将调用的Date对象转换为字符串并返回结果。 | 
获取当前日期和时间
这是一个非常简单的方法,在Java中获取当前日期和时间。您可以使用一个简单的Date对象,结合toString() 方法来打印当前的日期和时间,如下所示 −
示例
import java.util.Date;
public class DateDemo {
   public static void main(String args[]) {
      // Instantiate a Date object
      Date date = new Date();
      // display time and date using toString()
      System.out.println(date.toString());
   }
}
这将生成以下结果-
输出
on May 04 09:51:52 CDT 2009
日期比较
以下是比较两个日期的三种方法:
- 您可以使用getTime()方法获取从1970年1月1日午夜以来经过的毫秒数,然后比较这两个值。
 - 
您可以使用before(),after()和equals()方法。例如,因为一个月的第12天在18号之前,所以new Date(99,2,12).before(new Date(99,2,18))返回true。
 - 
您可以使用Comparable接口定义的compareTo()方法,该方法由Date类实现。
 
使用SimpleDateFormat进行日期格式化
SimpleDateFormat是一个具体类,用于以区域敏感的方式格式化和解析日期。SimpleDateFormat允许您从任意用户定义的日期时间格式开始。
示例
import java.util.*;
import java.text.*;
public class DateDemo {
   public static void main(String args[]) {
      Date dNow = new Date( );
      SimpleDateFormat ft = 
      new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
      System.out.println("Current Date: " + ft.format(dNow));
   }
}
这将产生以下结果 –
输出
Current Date: Sun 2004.07.18 at 04:14:09 PM PDT
简单日期格式代码
要指定时间格式,请使用时间模式字符串。在此模式中,所有的ASCII字母都被保留为模式字符,其定义如下—
| 字符 | 描述 | 示例 | 
|---|---|---|
| G | 公元 | AD | 
| y | 四位数年份 | 2001 | 
| M | 月份 | 七月或07 | 
| d | 日期 | 10 | 
| h | 上午/下午的小时(1~12) | 12 | 
| H | 一天中的小时(0~23) | 22 | 
| m | 分钟 | 30 | 
| s | 秒钟 | 55 | 
| S | 毫秒 | 234 | 
| E | 星期几 | 星期二 | 
| D | 年份中的天数 | 360 | 
| F | 一个月中第几个星期几 | 2(七月中第二个星期三) | 
| w | 年份中的周数 | 40 | 
| W | 一个月中的周数 | 1 | 
| a | 上午/下午 | PM | 
| k | 一天中的小时(1~24) | 24 | 
| K | 上午/下午的小时(0~11) | 10 | 
| z | 时区 | 东部标准时间 | 
| ‘ | 文本转义字符 | 分隔符 | 
| “ | 单引号 | ` | 
使用printf进行日期格式化
使用 printf 方法可以很容易地进行日期和时间格式化。您使用一个两个字母的格式,以 t 开头并以表格中的一个字母结尾,如下面的代码所示。
示例
import java.util.Date;
public class DateDemo {
   public static void main(String args[]) {
      // Instantiate a Date object
      Date date = new Date();
      // display time and date
      String str = String.format("Current Date/Time : %tc", date );
      System.out.printf(str);
   }
}
这将产生以下结果−
输出
Current Date/Time : Sat Dec 15 16:37:57 MST 2012
如果您必须多次提供日期来格式化每个部分,那将会有点愚蠢。因此,格式字符串可以指示要格式化的参数的索引。
索引必须紧跟在%之后,并且必须以$结束。
示例
import java.util.Date;
public class DateDemo {
   public static void main(String args[]) {
      // Instantiate a Date object
      Date date = new Date();
      // display time and date
      System.out.printf("%1s %2tB %2td, %2tY", "Due date:", date);
   }
}
这将会生成以下结果 –
输出
Due date: February 09, 2004
或者,您可以使用<标志。它表示应该再次使用上一个格式规范中的相同参数。
示例
import java.util.Date;
public class DateDemo {
   public static void main(String args[]) {
      // Instantiate a Date object
      Date date = new Date();
      // display formatted date
      System.out.printf("%s %tB %<te, %<tY", "Due date:", date);
   }
}
这将产生以下结果−
输出
Due date: February 09, 2004
日期和时间的转换字符
| 字符 | 描述 | 示例 | 
|---|---|---|
| c | 完整的日期和时间 | Mon May 04 09:51:52 CDT 2009 | 
| F | ISO 8601日期 | 2004-02-09 | 
| D | 美国格式的日期(月/日/年) | 02/09/2004 | 
| T | 24小时制时间 | 18:05:19 | 
| r | 12小时制时间 | 06:05:19 pm | 
| R | 24小时制时间,不包含秒数 | 18:05 | 
| Y | 四位数年份(前面有零) | 2004 | 
| y | 年份的最后两位(前面有零) | 04 | 
| C | 年份的前两位数(包括前导零) | 20 | 
| B | 完整月份名称 | 二月 | 
| b | 缩写月份名称 | 二月 | 
| m | 两位数月份(包括前导零) | 02 | 
| d | 两位数日期(包括前导零) | 03 | 
| e | 两位数日期(不包括前导零) | 9 | 
| A | 完整星期几名称 | 星期一 | 
| a | 缩写星期几名称 | 一 | 
| j | 三位数的年份日期(带前导零) | 069 | 
| H | 两位数的小时(带前导零),范围在00和23之间 | 18 | 
| k | 两位数的小时(没有前导零),范围在0和23之间 | 18 | 
| I | 两位数的小时(带前导零),范围在01和12之间 | 06 | 
| l | 两位数的小时(没有前导零),范围在1和12之间 | 6 | 
| M | 两位数的分钟(带前导零) | 05 | 
| S | 两位数的秒钟(带前导零) | 19 | 
| L | 三位数的毫秒(带前导零) | 047 | 
| N | 九位数的纳秒(包括前导零) | 047000000 | 
| P | 大写的上午或下午标记 | PM | 
| p | 小写的上午或下午标记 | pm | 
| z | 距离格林尼治标准时间的RFC 822数值偏移 | -0800 | 
| Z | 时区 | PST | 
| s | 自1970年01月01日00:00:00 GMT以来的秒数 | 1078884319 | 
| Q | 自1970年01月01日00:00:00 GMT以来的毫秒数 | 1078884319047 | 
在与日期和时间相关的其他实用类中,还有其他有用的类。有关更多详细信息,请参阅Java标准文档。
将字符串解析为日期
SimpleDateFormat类具有一些额外的方法,特别是parse()方法,它尝试根据给定SimpleDateFormat对象中存储的格式解析字符串。
示例
import java.util.*;
import java.text.*;
public class DateDemo {
   public static void main(String args[]) {
      SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd"); 
      String input = args.length == 0 ? "1818-11-11" : args[0]; 
      System.out.print(input + " Parses as "); 
      Date t;
      try {
         t = ft.parse(input); 
         System.out.println(t); 
      } catch (ParseException e) { 
         System.out.println("Unparseable using " + ft); 
      }
   }
}
上述程序的一个示例运行将产生以下结果−
输出
1818-11-11 Parses as Wed Nov 11 00:00:00 EST 1818
睡一会儿
你可以睡任意时间,从一毫秒到你的计算机的寿命。例如,下面的程序会睡3秒钟:
示例
import java.util.*;
public class SleepDemo {
   public static void main(String args[]) {
      try { 
         System.out.println(new Date( ) + "\n"); 
         Thread.sleep(5*60*10); 
         System.out.println(new Date( ) + "\n"); 
      } catch (Exception e) {
         System.out.println("Got an exception!"); 
      }
   }
}
这将产生以下结果
输出
Sun May 03 18:04:41 GMT 2009
Sun May 03 18:04:51 GMT 2009
测量经过的时间
有时候,你可能需要以毫秒来测量某个时间点。因此,让我们再次重新编写上面的示例 –
示例
import java.util.*;
public class DiffDemo {
   public static void main(String args[]) {
      try {
         long start = System.currentTimeMillis( );
         System.out.println(new Date( ) + "\n");
         Thread.sleep(5*60*10);
         System.out.println(new Date( ) + "\n");
         long end = System.currentTimeMillis( );
         long diff = end - start;
         System.out.println("Difference is : " + diff);
      } catch (Exception e) {
         System.out.println("Got an exception!");
      }
   }
}
这将生成以下结果−
输出
Sun May 03 18:16:51 GMT 2009
Sun May 03 18:16:57 GMT 2009
Difference is : 5993
GregorianCalendar类
GregorianCalendar是Calendar类的具体实现,它实现了你熟悉的标准公历。我们在本教程中没有讨论Calendar类,你可以查阅Java标准文档了解更多信息。
Calendar的getInstance()方法 返回一个GregorianCalendar对象,用默认区域设置和时区初始化为当前日期和时间。GregorianCalendar定义了两个字段:公元和公元前,代表了公历的两个时代。
GregorianCalendar对象还有几个构造方法:
| 编号 | 构造函数及说明 | 
|---|---|
| 1 | GregorianCalendar() 使用默认时区和默认语言环境构造一个默认的GregorianCalendar对象,时间为当前时间。 | 
| 2 | GregorianCalendar(int year, int month, int date) 使用默认时区和默认语言环境构造一个GregorianCalendar对象,设置给定的日期。 | 
| 3 | GregorianCalendar(int year, int month, int date, int hour, int minute) 使用默认时区和默认语言环境构造一个GregorianCalendar对象,设置给定的日期和时间。 | 
| 4 | GregorianCalendar(int year, int month, int date, int hour, int minute, int second) 使用默认时区和默认语言环境构造一个GregorianCalendar对象,设置给定的日期和时间。 | 
| 5 | GregorianCalendar(Locale aLocale) 使用默认时区和给定的语言环境构造一个基于当前时间的GregorianCalendar对象。 | 
| 6 | GregorianCalendar(TimeZone zone) 使用给定的时区和默认语言环境构造一个基于当前时间的GregorianCalendar对象。 | 
| 7 | GregorianCalendar(TimeZone zone, Locale aLocale) 使用给定的时区和语言环境构造一个基于当前时间的GregorianCalendar对象。 | 
以下是GregorianCalendar类提供的一些有用的支持方法列表:
| 编号 | 方法和描述 | 
|---|---|
| 1 | void add(int field, int amount) 根据日历规则,在给定的时间字段上添加指定的(有符号的)时间量。 | 
| 2 | protected void computeFields() 将UTC时间(以毫秒为单位)转换为时间字段值。 | 
| 3 | protected void computeTime() 覆盖日历,将时间字段值转换为UTC时间(以毫秒为单位)。 | 
| 4 | boolean equals(Object obj) 将此GregorianCalendar与对象引用进行比较。 | 
| 5 | int get(int field) 获取给定时间字段的值。 | 
| 6 | int getActualMaximum(int field) 返回给定日期的当前字段可能具有的最大值。 | 
| 7 | int getActualMinimum(int field) 返回给定日期的当前字段可能具有的最小值。 | 
| 8 | int getGreatestMinimum(int field) 返回给定字段的最高最小值(如果存在)。 | 
| 9 | Date getGregorianChange() 获取儒略历日历更改日期。 | 
| 10 | int getLeastMaximum(int field) 返回给定字段的最低最大值(如果存在)。 | 
| 11 | int getMaximum(int field) 返回给定字段的最大值。 | 
| 12 | Date getTime() 获取这个日历的当前时间。 | 
| 13 | long getTimeInMillis() 以long类型获取这个日历的当前时间。 | 
| 14 | TimeZone getTimeZone() 获取时区。 | 
| 15 | int getMinimum(int field) 返回给定字段的最小值。 | 
| 16 | int hashCode() 重写hashCode。 | 
| 17 | boolean isLeapYear(int year) 确定给定的年份是否是闰年。 | 
| 18 | void roll(int field, boolean up) 在给定的时间字段上添加或减去(向上/向下)一个单位的时间,而不改变更大的字段。 | 
| 19 | void set(int field, int value) 将给定的值设置为时间字段的值。 | 
| 20 | void set(int year, int month, int date) 设置年、月和日期字段的值。 | 
| 21 | void set(int year, int month, int date, int hour, int minute) 设置年、月、日期、小时和分钟字段的值。 | 
| 22 | void set(int year, int month, int date, int hour, int minute, int second) 设置字段year、month、date、hour、minute和second的值。 | 
| 23 | void setGregorianChange(Date date) 设置GregorianCalendar变更日期。 | 
| 24 | void setTime(Date date) 用给定的Date设置此Calendar的当前时间。 | 
| 25 | void setTimeInMillis(long millis) 从给定的long值设置此Calendar的当前时间。 | 
| 26 | void setTimeZone(TimeZone value) 使用给定的时区值设置时区。 | 
| 27 | String toString() 返回此日历的字符串表示形式。 | 
示例
import java.util.*;
public class GregorianCalendarDemo {
   public static void main(String args[]) {
      String months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", 
         "Oct", "Nov", "Dec"};
      int year;
      // Create a Gregorian calendar initialized
      // with the current date and time in the
      // default locale and timezone.
      GregorianCalendar gcalendar = new GregorianCalendar();
      // Display current time and date information.
      System.out.print("Date: ");
      System.out.print(months[gcalendar.get(Calendar.MONTH)]);
      System.out.print(" " + gcalendar.get(Calendar.DATE) + " ");
      System.out.println(year = gcalendar.get(Calendar.YEAR));
      System.out.print("Time: ");
      System.out.print(gcalendar.get(Calendar.HOUR) + ":");
      System.out.print(gcalendar.get(Calendar.MINUTE) + ":");
      System.out.println(gcalendar.get(Calendar.SECOND));
      // Test if the current year is a leap year
      if(gcalendar.isLeapYear(year)) {
         System.out.println("The current year is a leap year");
      }else {
         System.out.println("The current year is not a leap year");
      }
   }
}
这将产生以下结果−
输出
Date: Apr 22 2009
Time: 11:25:27
The current year is not a leap year
完整的Calendar类可用常量列表,请参考标准的Java文档。
极客教程