掌握 Java 日期时间:构造器、方法与最佳实践
Java 在 java.util 包提供 Date 类,封装当前日期时间。
Date 类支持两个构造器:
| 序号 | 构造器 & 描述 |
|---|---|
| 1 | Date() - 用当前日期时间初始化对象。 |
| 2 | Date(long millisec) - 接受参数为自 1970 年 1 月 1 日午夜起经过的毫秒数。 |
Date 类方法如下:
| 序号 | 方法 & 描述 |
|---|---|
| 1 | boolean after(Date date) - 调用 Date 对象包含的日期晚于指定 date 返回 true,否则 false。 |
| 2 | boolean before(Date date) - 调用 Date 对象日期早于指定 date 返回 true,否则 false。 |
| 3 | Object clone() - 复制调用 Date 对象。 |
| 4 | int compareTo(Date date) - 比较调用对象值与 date。值相等返回 0;调用对象早于 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 设置时间日期,time 为自 1970 年 1 月 1 日午夜起毫秒数。 |
| 10 | String toString() - 将调用 Date 对象转为字符串返回。 |
获取当前日期时间
获取当前日期时间很简单。用简单 Date 对象配合 toString() 打印:
示例
Live Demoimport java.util.Date;
public class DateDemo {
public static void main(String args[]) {
Date date = new Date();
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。
- 用 compareTo() 方法,由 Comparable 接口定义并由 Date 实现。
使用 SimpleDateFormat 格式化日期
SimpleDateFormat 是具体类,以区域敏感方式格式化和解析日期。允许用户自定义日期时间格式模式。
示例
Live Demoimport 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
SimpleDateFormat 格式代码
指定时间格式用时间模式字符串。模式中所有 ASCII 字母保留为模式字母,定义如下:
| 字符 | 描述 | 示例 |
|---|---|---|
| G | 纪元标志 | AD |
| y | 四位年份 | 2001 |
| M | 年份中月份 | July 或 07 |
| d | 月份中天数 | 10 |
| h | 上午/下午小时 (1~12) | 12 |
| H | 一天中小时 (0~23) | 22 |
| m | 小时中分钟 | 30 |
| s | 分钟中秒数 | 55 |
| S | 毫秒 | 234 |
| E | 周中天数 | Tuesday |
| D | 年份中天数 | 360 |
| F | 月份中周几 | 2 (七月第二个周三) |
| w | 年份中周数 | 40 |
| W | 月份中周数 | 1 |
| a | 上午/下午标记 | PM |
| k | 一天中小时 (1~24) | 24 |
| K | 上午/下午小时 (0~11) | 10 |
| z | 时区 | Eastern Standard Time |
| ' | 文本转义 | 分隔符 |
| " | 单引号 | ` |
使用 printf 格式化日期
日期时间格式化可用 printf 方法轻松完成。用两字母格式,以 t 开头,以表中字母结尾。
示例
Live Demoimport java.util.Date;
public class DateDemo {
public static void main(String args[]) {
Date date = new 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
若需多次提供日期格式化各部分会很繁琐。因此格式字符串可指示要格式化的参数索引。
索引必须紧跟 % 并以 $ 终止。
示例
Live Demoimport java.util.Date;
public class DateDemo {
public static void main(String args[]) {
Date date = new Date();
System.out.printf("%1$s %2$tB %2$td, %2$tY", "Due date:", date);
}
}
输出:
输出
Due date: February 09, 2004
也可用 < 标志。表示使用前一个格式规范相同参数。
示例
Live Demoimport java.util.Date;
public class DateDemo {
public static void main(String args[]) {
Date date = new 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 | 完整月份名 | February |
| b | 缩写月份名 | Feb |
| m | 两位月份 (前导零) | 02 |
| d | 两位日期 (前导零) | 03 |
| e | 两位日期 (无前导零) | 9 |
| A | 完整星期名 | Monday |
| a | 缩写星期名 | Mon |
| 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 GMT 数字偏移 | -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 对象存储的格式解析字符串。
示例
Live Demoimport 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
休眠一段时间
可休眠 1 毫秒至计算机寿命任意时长。例:以下程序休眠 3 秒:
示例
Live Demoimport 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
测量 elapsed 时间
有时需测量毫秒级时间点。重写上例:
示例
Live Demoimport 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 文档。
getInstance() 方法返回用当前日期时间初始化的 GregorianCalendar,采用默认区域和时区。GregorianCalendar 定义 AD 和 BC 两个字段,代表公历定义的两个纪元。
GregorianCalendar 有多个构造器:
| 序号 | 构造器 & 描述 | |
|---|---|---|
| 1 | GregorianCalendar() - 用默认时区/区域当前时间构造默认 GregorianCalendar。 | |
| 2 | GregorianCalendar(int year, int month, int date) - 用给定日期在默认时区/区域构造。 | |
| 3 | GregorianCalendar(int year, int month, int date, int hour, int minute) - 用给定日期时间在默认时区/区域构造。 | |
| 4 | GregorianCalendar(int year, int month, int date, int hour, int minute, int second) - 用给定日期时间在默认时区/区域构造。 | |
| 5 | GregorianCalendar(Locale aLocale) | 基于默认时区当前时间和给定区域构造。 |
| 6 | GregorianCalendar(TimeZone zone) - 基于给定时区当前时间和默认区域构造。 | |
| 7 | GregorianCalendar(TimeZone zone, Locale aLocale) - 基于给定时区当前时间和给定区域构造。 |
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() - 获取此 Calendar 当前时间。 |
| 13 | long getTimeInMillis() - 获取此 Calendar 当前时间长整型。 |
| 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) - 设置年、月、日、时、分、秒字段值。 |
| 23 | void setGregorianChange(Date date) - 设置公历切换日期。 |
| 24 | void setTime(Date date) - 用给定 Date 设置此 Calendar 当前时间。 |
| 25 | void setTimeInMillis(long millis) - 用给定长整型值设置此 Calendar 当前时间。 |
| 26 | void setTimeZone(TimeZone value) - 用给定时区值设置时区。 |
| 27 | String toString() - 返回此日历字符串表示。 |
示例
Live Demoimport 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;
// 创建用默认区域/时区当前日期时间初始化的公历日历
GregorianCalendar gcalendar = new GregorianCalendar();
// 显示当前时间日期信息
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));
// 测试当前年是否闰年
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 文档。
java