当前位置:网站首页>Format method and parse method of dateformat class

Format method and parse method of dateformat class

2022-06-24 20:57:00 Platonic

format Methods and parse Method
String format(Date date)
 In the specified format , hold Date The date is converted to a string that matches the pattern .
parse(String obj)
 Format the text as a date 

The following example demonstrates :

public class Demo03DataFormat {
    public static void main(String[] args) throws ParseException {
//         Use DateFormat Class format Method , Format the date as text 
        //String format(Date date)  In the specified format , hold Date The date is converted to a string that matches the pattern 
        demo01();
        System.out.println("================");// Split line 
        demo02();
    }
    public static void demo01(){
        //1. establish SimpleDateFormat object , Pass the specified pattern in the constructor 
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //2. call SimpleDateFormat Methods in objects format, According to the pattern specified by the constructor , hold Date The date is formatted as a pattern string /
        Date date=new Date();
        String format = sdf.format(date);
        System.out.println(format);
        System.out.println(date);
    }

    // Use DateFormat Class parse Method , Format the text as a date 
    public static void demo02() throws ParseException {
        //1. establish SimpleDateFormat object , Pass the specified pattern in the constructor 
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy year MM month dd Japan  HH when mm branch ss second ");
        //parse An error will be reported here , Two solutions :1. Use throws Throw an exception .2. Use try...catch... Handle 
        Date parse = sdf.parse("2022 year 01 month 22 Japan  16 when 34 branch 51 second ");
                                                                                                    
        System.out.println(parse);
    }
}

java.util.Date Two common methods

原网站

版权声明
本文为[Platonic]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202211325384199.html