Dateformat类的format方法和parse方法

Dateformat类的format方法和parse方法,第1张

Dateformat类的format方法和parse方法 format方法和parse方法
String format(Date date)
按照指定的格式,把Date日期转化为符合模式的字符串。
parse(String obj)
把文本格式化为日期

下面示例演示:

public class Demo03DataFormat {
    public static void main(String[] args) throws ParseException {
//        使用DateFormat类中的format方法,把日期格式化为文本
        //String format(Date date) 按照指定的格式,把Date日期转化为符合模式的字符串
        demo01();
        System.out.println("================");//分割线
        demo02();
    }
    public static void demo01(){
        //1.创建SimpleDateFormat对象,构造方法中传递指定的模式
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //2.调用SimpleDateFormat对象中的方法format,按照构造方法指定的模式,把Date日期格式化为符合模式的字符串/
        Date date=new Date();
        String format = sdf.format(date);
        System.out.println(format);
        System.out.println(date);
    }

    //使用DateFormat类中的parse方法,把文本格式化为日期
    public static void demo02() throws ParseException {
        //1.创建SimpleDateFormat对象,构造方法中传递指定的模式
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
        //parse在此会报错,两个解决办法:1.使用throws抛出异常。2.使用try...catch...处理
        Date parse = sdf.parse("2022年01月22日 16时34分51秒");
                                                                                                    
        System.out.println(parse);
    }
}

java.util.Date常用的两个方法

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/zaji/5709092.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-17
下一篇2022-12-17

发表评论

登录后才能评论

评论列表(0条)

    保存