时间日期类Date类、Calendar类
目标:
- Date类进行毫秒值和时间对象的转换。
getTime()
方法和setTime()
方法 - SimpleFormat类进行指定模式下日期和字符串的转换。
构造方法SimpleDateFormat(String pattern)
给定模式
String format(Date date)
和Date parse(String source)
进行转换 - Clander类获取日历字段,
int get(int field)
对日历字段进行操作。add(int field, int amount)
和set(int year, int month, int date)
方法
1. Date类概述
java.util包下的类 Date 表示特定的瞬间,精确到毫秒。
(1) 构造方法
Date()
根据当前默认毫秒值创建日期对象,从1970年1月1日 00:00:00 GMT起计算
Date(long date)
根据给定的毫秒值创建日期对象。
注意时区。
示例:
package cn.itcast;
import java.util.Date;
public class demo {
public static void main(String[] args) {
Date d1 = new Date(); //无参构造方法默认为当前毫秒值
System.out.println(d1); //直接输出相当于调用toString方法
Date d2 = new Date(System.currentTimeMillis()); //用System.currentTimeMillis()获取当前毫秒值
System.out.println(d2);
Date d3 = new Date(1000*60*60); //1个小时的毫秒值
System.out.println(d3); //输出为9点,是因为8个小时的时差
}
}
结果:
Sat Mar 07 14:51:16 CST 2020
Sat Mar 07 14:51:16 CST 2020
Thu Jan 01 09:00:00 CST 1970
(2) 常用方法
日期和毫秒值的之间相互转换
long getTime()
获取此 Date 对象表示的毫秒数。 日期–>毫秒
void setTime(long time)
设置时间。 毫秒–>日期
2. DateFormat类实现日期和字符串的转换
java.text.DateFormat是日期/时间格式化子类的抽象类,它以与语言无关的方式格式化并解析日期或时间。
有一个日期/时间格式化子类java.text.SimpleDateFormat可以对日期进行格式化(也就是日期 -> 文本)、解析(文本-> 日期)和标准化。
(1) SimpleDateFormat的构造方法
SimpleDateFormat()
默认的模式和默认语言环境的日期格式符号
SimpleDateFormat(String pattern)
给定的模式和默认语言环境的日期格式符号
给定模式:
y ----- 年
M ----- 年中的月份
d ----- 月份中的天数
H----- 一天中的小时数(0-23)
m----- 小时中的分钟数
s ----- 分钟中的秒数
(2) 格式化方法format()和解析文本方法parse()
String format(Date date)
将一个 Date 按照指定模式格式化为日期/时间字符串。
Date parse(String source)
从给定字符串的解析文本,生成一个日期。 要注意格式必须匹配。
示例:
package cn.itcast;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class demo {
public static void main(String[] args) throws ParseException {
Date d = new Date(); //创建Date对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //给定模式
System.out.println(sdf.format(d)); //按照给定模式格式化Date对象得到字符串
System.out.println(sdf.parse("2008-08-08 12:12:12")); //按照给定模式解析字符串得到Date对象
}
}
输出结果:
2020-03-07 15:13:42
Fri Aug 08 12:12:12 CST 2008
3. 日历类Calendar类
java.util.Calendar 是一个抽象类 ,提供了一些日历字段YEAR、MONTH、DAY_OF_MONTH、HOUR、MINUTE 和 SECOND 与特定瞬间的转换功能。每一个日历字段都是静态的成员变量。要注意月份的范围是0~11。
(1) 获取日历字段
static Calendar getInstance()
返回Calendar,实际上返回的是其子类对象
int get(int field)
返回给定日历字段的值。
package cn.itcast;
import java.util.Calendar;
public class demo {
public static void main(String[] args) {
Calendar rightNow = Calendar.getInstance(); //实际上返回的是其子类对象
int year = rightNow.get(Calendar.YEAR); //获取年
int month = rightNow.get(Calendar.MONTH); //获取月,注意范围是0~11
int day = rightNow.get(Calendar.DAY_OF_MONTH); //获取日
System.out.println(year+"年"+(month+1)+"月"+day+"日"); //输出当前时间
}
}
输出结果:
2020年3月7日
(2) add()和set()方法修改和设置日历
void add(int field, int amount)
对给定的日历字段进行增减负数则为减
void set(int year, int month, int date)
根据给定的字段设置日历