SimpleDateFormat和DateTimeFormatter都可以实现:
①将日期格式化成日期/时间字符串
②从给定字符串的开始解析文本以生成日期
SimpleDateFormat是针对java.util.date和java.sql.date进行操作
DateTimeFormatter是针对jdk1.8新增日期API进行转换操作
一 .SimpleDateFormat
1.SimpleDateFormat的构造方法
方法名 | 说明 |
public SimpleDateFormat() | 构造一个SimpleDateFormat,使用默认模式和日期格式 |
public SimpleDateFormat(String pattern) | 构造一个SimpleDateFormat使用给定的模式和默认的日期格式 |
2.SimpleDateFormat格式化和解析日期
1、格式化(从Date到String)
public final String format(Date date):将日期格式化成日期/时间字符串
2、解析(从String到Date)
public Date pase(String source):从给定字符串的开始解析文本以生成日期
代码:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatDemo {
public static void main(String[] args) throws ParseException {
//格式化:从Date到String
Date d = new Date();//获取当前系统的时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String s = sdf.format(d);
System.out.println(s);
System.out.println("--------");
//解析:从String到Date
String ss = "2022-03-20 20:20:20";
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dd = sdf2.parse(ss);
System.out.println(dd);
}
}
运行结果:
二 .DateTimeFormatter
自定义的格式。如: ofPattern( "yyyy-MM-dd hh:mm:ss") ---》重点,以后常用
DateTimeFormatter df3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
public class Test10 {
//这是一个main方法,是程序的入口:
public static void main(String[] args) {
//格式化类:DateTimeFormatter
//方式一:预定义的标准格式。如: ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;IS0_LOCAL_TIME
DateTimeFormatter df1 = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
//df1就可以帮我们完成LocalDateTime和String之间的相互转换:
//LocalDateTime-->String:
LocalDateTime now = LocalDateTime.now();
String str = df1.format(now);
System.out.println(str);//2020-06-15T15:02:51.29
//String--->LocalDateTime
TemporalAccessor parse = df1.parse("2020-06-15T15:02:51.29");
System.out.println(parse);
//方式二:本地化相关的格式。如: oflocalizedDateTime()
//参数:FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT
//FormatStyle.LONG :2020年6月15日 下午03时17分13秒
//FormatStyle.MEDIUM: 2020-6-15 15:17:42
//FormatStyle.SHORT:20-6-15 下午3:18
DateTimeFormatter df2 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
//LocalDateTime-->String:
LocalDateTime now1 = LocalDateTime.now();
String str2 = df2.format(now1);
System.out.println(str2);
//String--->LocalDateTime
TemporalAccessor parse1 = df2.parse("20-6-15 下午3:18");
System.out.println(parse1);
//方式三: 自定义的格式。如: ofPattern( "yyyy-MM-dd hh:mm:ss") ---》重点,以后常用
DateTimeFormatter df3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
//LocalDateTime-->String:
LocalDateTime now2 = LocalDateTime.now();
String format = df3.format(now2);
System.out.println(format);//2020-06-15 03:22:03
//String--->LocalDateTime
TemporalAccessor parse2 = df3.parse("2020-06-15 03:22:03");
System.out.println(parse2);
}
}