简单介绍
DateFormat 类可以将一个 日期/时间 对象 格式化为表示某个国家地区的 日期/时间 字符串 或者使用 parse 方法 将字符串解析为日期/时间对象
注意: parse 和 format 方法 完全相反,一个 是把 date 时间转为相应地区和国家的显示样式,一个是把相应地区的时间日期转为 date对象,parse方法在使用的时候,解析的时间或日期要符合指定的国家,地区格式,否则会抛异常
DaateFormat 类定义了一些用于描述日期/时间的显示模式的 int 型常量,包括 FULL , LONG, MEDIUM, DEFAULT, SHORT,实例化 DateFormat 对象时,可以使用这些常量,控制 日期/时间的 显示长度
使用案例:
package cn.domain;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.Locale;
public class DateFormatDemo {
public static void main(String[] args) throws ParseException {
Date date = new Date();
//1 中文环境下的SHORT类型的日期
DateFormat df1 = DateFormat.getDateInstance(DateFormat.SHORT, Locale.CHINA);
System.out.println(df1.format(date));// 输出: 17-9-21
//2 英文环境下的SHORT类型的日期
DateFormat df2 = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
System.out.println(df2.format(date));// 输出: 9/21/17
//3中文环境下的SHORT类型的日期时间
DateFormat df3 = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT, Locale.CHINA);
System.out.println(df3.format(date));// 输出: 17-9-21 下午12:16
//4 英文环境下的SHORT类型的日期时间
DateFormat df4 = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT, Locale.US);
System.out.println(df4.format(date));// 输出: 9/21/17 12:16 PM
//5 中文环境下的 SHORT类型的日期,LONG型的时间
DateFormat df5 = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.LONG, Locale.CHINA);
System.out.println(df5.format(date));// 输出: 17-9-21 下午12时18分10秒
//6 将字符串解析为 时间对象
String date1 = "17-9-21 下午12时18分10秒";
DateFormat df6 = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.LONG, Locale.CHINA);
Date d = df6.parse(date1);
System.out.println(d);// 输出 : Thu Sep 21 12:18:10 CST 2017
}
}