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

 1 import java.sql.Date;
 2 import java.text.ParseException;
 3 import java.text.SimpleDateFormat;
 4 public class DateFormat {
 5 
 6 public static void main(String[] args) throws ParseException {
 7 //先实验下格式化的过程,显示当前的时间
 8 
 9 //首先提取现在的时间
10 Date d = new Date(System.currentTimeMillis());
11 
12 //格式化这个时间,首先用默认模式
13 SimpleDateFormat sdf = new SimpleDateFormat();
14 
15 //public StringBuffer format(Date date,StringBuffer toAppendTo,FieldPosition pos)
16 //将给定的 Date 格式化为日期/时间字符串,并将结果添加到给定的 StringBuffer。 
17 String s = sdf.format(d);
18 //输出字符串
19 System.out.println(s);//16-9-19 下午6:19
20 
21 //格式化时间,用自己设定的模式
22 SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
23 
24 //将给定的 Date 格式化为日期/时间字符串,并将结果添加到给定的 StringBuffer。 
25 String s1 = sdf1.format(d);
26 //输出字符串
27 System.out.println(s1); //2016-09-19 18:21:25
28 
29 
30 //实验下解析的过程。注意:在把一个字符串解析为日期的时候,请注意格式必须和给定的字符串格式匹配
31 /* 
32 //先设定一个时间字符串,符合模式的
33 String t = "2016-09-19 18:21:25";
34 
35 //再设定模式
36 SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
37 
38 //String - Date 进行解析 public Date parse(String source);
39 Date d1 = (Date) sdf2.parse(t);jdk1.8时,这句不能运行。
40 下面的是从教程中拉过来的,导入后能运行。
41 System.out.println(d1);
42 
43 */
44 
45 //String -- Date
46 String str = "2016-08-08 12:12:12";
47 //在把一个字符串解析为日期的时候,请注意格式必须和给定的字符串格式匹配
48 SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
49 //String - Date 进行解析 public Date parse(String source);
50 Date dd = sdf2.parse(str);
51 System.out.println(dd);
52 }
53 
54 }

 

posted @ 2016-09-19 20:23  卡拉瓦  阅读(273)  评论(0编辑  收藏  举报