java 14 - 8 DateFormat

时间:2023-03-09 19:52:59
java 14 - 8 DateFormat

  A、有时候在网站注册账号时,会有日期选项,下面会有一个小型的日历可供选择。这个日期其实是个String类,
选择了日期之后,这个String类会通过程序,转换为Date类,再存入数据库中。
  B、反之,这个小型日历的形成,也是从数据库中提取出Date类,再通过程序转换为String类显示出来。

  而A中的过程,其实就是 String -- Date(解析)
    public Date parse(String source)

  B中的过程,其实就是 Date -- String(格式化)
    public final String format(Date date)
  DateForamt:可以进行日期和字符串的格式化和解析,但是由于是抽象类,所以使用具体子类 SimpleDateFormat。

  SimpleDateFormat的构造方法:
  SimpleDateFormat():默认模式 (就是年月日时分秒挤在一起显示)
  SimpleDateFormat(String pattern):给定的模式 (自己提供显示模式)

  在把一个字符串解析为日期的时候,请注意格式必须和给定的字符串格式匹配
  这个模式字符串该如何写呢?
  通过查看API,我们就找到了对应的模式
      年     y
      月     M
      日     d
      时     H
      分     m
      秒     s

 import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class DateFormat { public static void main(String[] args) throws ParseException {
//先实验下格式化的过程,显示当前的时间 //首先提取现在的时间
Date d = new Date(System.currentTimeMillis()); //格式化这个时间,首先用默认模式
SimpleDateFormat sdf = new SimpleDateFormat(); //public StringBuffer format(Date date,StringBuffer toAppendTo,FieldPosition pos)
//将给定的 Date 格式化为日期/时间字符串,并将结果添加到给定的 StringBuffer。
String s = sdf.format(d);
//输出字符串
System.out.println(s);//16-9-19 下午6:19 //格式化时间,用自己设定的模式
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //将给定的 Date 格式化为日期/时间字符串,并将结果添加到给定的 StringBuffer。
String s1 = sdf1.format(d);
//输出字符串
System.out.println(s1); //2016-09-19 18:21:25 //实验下解析的过程。注意:在把一个字符串解析为日期的时候,请注意格式必须和给定的字符串格式匹配
/*
//先设定一个时间字符串,符合模式的
String t = "2016-09-19 18:21:25"; //再设定模式
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //String - Date 进行解析 public Date parse(String source);
Date d1 = (Date) sdf2.parse(t);jdk1.8时,这句不能运行。
下面的是从教程中拉过来的,导入后能运行。
System.out.println(d1); */ //String -- Date
String str = "2016-08-08 12:12:12";
//在把一个字符串解析为日期的时候,请注意格式必须和给定的字符串格式匹配
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//String - Date 进行解析 public Date parse(String source);
Date dd = sdf2.parse(str);
System.out.println(dd);
} }

java 14 - 8 DateFormat