DateFormat类介绍
java.text.DateFormat类
public abstract class DateFormat extends Format
DateFormat 是日期/时间格式化子类的抽象类==>DateFormat是Format类的子类,DateFormat类本身还是一个抽象类,无法直接创建对象使用
DateFormat作用:
它以与语言无关的方式格式化并解析日期或时间
格式化(也就是日期 -> 文本)
解析(文本-> 日期
DateFormat类的成员方法:
String format(Date date) 参数传递Date日期,把日期格式化为符合模式的字符串
Date parse(String source) 参数传递字符串,把符合模式的字符串解析为Date日期
-----------------------------------------------------------------------------------------
DateFormat类本身还是一个抽象类,无法直接创建对象使用,需要使用DateFormat类的子类创建对象使用
java.text.SimpleDateFormat extends DateFormat类
SimpleDateFormat类的构造方法:
SimpleDateFormat(String pattern)
用给定的模式和默认语言环境的日期格式符号构造 SimpleDateFormat。
参数:
String pattern:传递日期和时间的模式
在模式中写y代表年
在模式中写M代表月
在模式中写d代表日
在模式中写H代表时
在模式中写m代表分
在模式中写s代表秒
"yyyy-MM-dd HH:mm:ss" "2020-08-10 11:56:03"
"yyyy年MM月dd日 HH时mm分ss秒" "2021年3月19日 11:10:22"
"yyyy/MM/dd HH:mm:ss"
注意:
1.表示模式的字母不能随便写(y代表年,M代表月...),表示年月日时分秒的连接符号可以随意写(-,/...)
2.表示模式的字母严格区分大小写
DataFormat类的常用方法
package com.itheima.demo06DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
DateFormat类的成员方法:
format:格式化
String format(Date date) 参数传递Date日期,把日期格式化为符合模式的字符串
使用步骤:
1.创建SimpleDateFormat对象,构造方法中传递指定的模式
2.使用SimpleDateFormat对象中的方法format,把日期格式化为符合模式的字符串
*/
public class Demo01Format {
public static void main(String[] args) {
//1.创建SimpleDateFormat对象,构造方法中传递指定的模式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//2.使用SimpleDateFormat对象中的方法format,把日期格式化为符合模式的字符串
Date date = new Date();
System.out.println(date);//Fri Mar 18 14:48:35 CST 2022
String s = sdf.format(date);
System.out.println(s);//2022-03-18 14:49:00
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
String s2 = sdf2.format(date);
System.out.println(s2);//2022年03月18日 14时49分53秒
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy年MM月dd日");
String s3 = sdf3.format(date);
System.out.println(s3);//2022年03月18日
}
}
package com.itheima.demo06DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
DateFormat类的成员方法:
parse:解析
Date parse(String source) 参数传递字符串,把符合模式的字符串解析为Date日期
使用步骤:
1.创建SimpleDateFormat对象,构造方法中传递指定的模式
2.使用SimpleDateFormat中的方法parse,把符合模式的字符串解析为Date日期
*/
public class Demo02parse {
public static void main(String[] args) throws ParseException {
//1.创建SimpleDateFormat对象,构造方法中传递指定的模式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
/*
2.使用SimpleDateFormat中的方法parse,把符合模式的字符串解析为Date日期
public Date parse(String source) throws ParseException
parse方法使用throws关键字声明抛出了ParseException解析异常
如果我们调用parse传递字符串参数"2022-3-18"和构造方法中模式不匹配,程序就会抛出异常
解决:
调用了一个抛出异常的方法,需要把异常解决:鼠标放在红线处,alt+回车,选择第一个
*/
//Date date = sdf.parse("2022-318");//ParseException: Unparseable date: "2022-318"
Date date = sdf.parse("2022-3-18");//Fri Mar 18 00:00:00 CST 2022
System.out.println(date);
}
}