Java中的SimpleDateFormat()方法

0.类介绍

SimpleFormat是一个具体类,这个类使用一种对地区敏感的方式(与语言环境有关的方式)去格式化、解析日期。它允许格式日期,解析日期,并且格式化。

1.简要代码

package test.shen.liu.enmonster;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test {
    public static void main(String args[]) throws ParseException {
        SimpleDateFormat sdf1 = new SimpleDateFormat();//build default pattern
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy.MM.dd  HH:mm:ss z");

        System.out.println(sdf1.toPattern());//output the default pattern
        System.out.println(sdf2.toPattern());//output first customized pattern
        System.out.println(sdf3.toPattern());//output second customized pattern
        System.out.println("==============================");

        Test t = new Test();
        String dateTime1 = "2018-03-13  15:32:34";
        String dateTime2 = "2018.03.13  15:32:34 GMT";//GMT correspond to sdf3's 'z'
        Date date = new Date();

        //System.out.println("Result 1:"+t.dateUtil(sdf1,dateTime1)); Error can't parse unknown date pattern
        System.out.println("Result 1:\t"+sdf1.format(date));
        System.out.println("Result 2:\t"+t.dateUtil(sdf2,dateTime1));
        System.out.println("Result 3:\t"+sdf2.format(date));//get system current datetime 获取系统当前时间
        System.out.println("Result 4:\t"+t.dateUtil(sdf3,dateTime2));
    }

    //return a date
    public Date dateUtil(SimpleDateFormat sdf,String dateTime) throws ParseException {
        Date da = new Date();
        //da = sdf.parse("20180318"); //Error the cause is that format isn't right
        da = sdf.parse(dateTime);//format date according to passing sdf
        return da;
    }
}

2.执行结果

yy-M-d ah:mm
yyyy-MM-dd  HH:mm:ss
yyyy.MM.dd  HH:mm:ss z
==============================
Result 1:	18-9-2 上午10:44
Result 2:	Tue Mar 13 15:32:34 CST 2018
Result 3:	2018-09-02  10:44:30
Result 4:	Tue Mar 13 23:32:34 CST 2018
========================================== update on 2018-10-06 ======================

3.Date的用法

如果对于没有使用SimpleDateFormat的代码,则会是下面这个样子。

    public static  void test(){
        Date date = new Date();
        System.out.println("date :" + date);
    }

输出如下:

date :Sat Oct 06 14:51:08 CST 2018