一、计算机纪元(0毫秒)
计算机 时间纪元是1970年1月1日 00:00:00,即计算机时间戳就是以该时间点为计时起点时间。
但是中国在东八区,所以此时中国的时间相当于1970年1月1日 08:00:00。
//测试时间纪元
public class TEST {
public static void main(String[] args) {
//long time = System.currentTimeMillis();
System.out.println( new Date(0));
}
}
结果:
二、JAVA Date类
1、构造方法:
//无参构造函数
Date date = new Date();
//有参构造函数,传入参数为距离时间纪元的毫秒数
Date date = new Date(long time); //参数为long型
2、内置方法
方法名 | 描述 | |
---|---|---|
1 | boolean after(Date date) | 调用此方法的对象在传入date的日期之后,返回true,否则返回false |
2 | boolean before(Date date) | 与after()方法相反 |
3 | boolean equals(Object date | 调用方法对象和传入参数相等时返回true,否则返回false |
4 | long getTime() | 获取从时间纪元到现在的毫秒数 |
5 | void setTime(long time) | 重新设置日期,传入参数为距时间纪元(1970年1月1日 00:00:00)的毫秒数 |
6 | String toString() | 将时间转换为字符串 |
… | … | … |
三、Date格式转换
1、DateFormat
位于java.text中,是日期、时间格式化子类的抽象类,其作用:
格式化:日期->文本
解 析:文本->日期
2、SimpleDateFormat
因为DateFormat是抽象类,无法直接创建对象使用,可以使用其子类SimpleDateFormat
//构造函数,指定对应的格式
SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd HH:mm:dd");
//Date转为字符串
String str = sft.format(date);
//字符串转Date
try {
date = sft.parse(str);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
例:
//long time = System.currentTimeMillis();
SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd HH:mm:dd");
//Date转字符串
Date date = new Date();
String str = sft.format(date);
System.out.println("时间1: [" + str + "]");
//字符串转Date
String strDate = "2021-01-01 00:00:00";
Date date1 = null;
try {
date1 = sft.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("时间2: [" + date1 + "]");
结果:
3、时间模式
字母 | 描述 | 距离 | |
---|---|---|---|
1 | G | 纪元标识 | 公元 |
2 | y | 年(4位,yyyy) | |
3 | M | 月 | |
4 | d | 日 | |
5 | h | 时,12小时制 | |
6 | H | 时,24小时制 | |
7 | m | 分 | |
8 | s | 秒 | |
9 | S | 毫秒 | |
10 | E | 星期几 | |
11 | D | 一年中的日子 | |
12 | F | 一个月中第几周的周几 | |
13 | w | 一年中第几周 | |
14 | W | 一个月中第几周 | |
15 | ’ | 文字界定符 |
注:允许多位,然后补0
SimpleDateFormat sft = new SimpleDateFormat("G yyyy-MM-ddd HH:mm:dd SSSS");