SimpleDateFormat和DateTimeFormatter的区分

SimpleDateFormat和DateTimeFormatter的区分

package com.heima.homework;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

//SimpleDateFormat和DateTimeFormatter的区分
public class T02 {
    public static void main(String[] args) throws ParseException {
      
  String s="2018-03-04";

        //1.用SimpleDateFormat有参构造创建一个对象simpleDateFormat
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //2.调用simpleDateFormat的parse(String)方法,将String转化为date类型。完成解析
        Date parse = simpleDateFormat.parse(s);

        //1.用SimpleDateFormat有参构造创建一个对象simpleDateFormat
        SimpleDateFormat sa = new SimpleDateFormat("yyyy年MM月dd日");
        //2.调用simpleDateFormat的format(date)方法,将date类型转化为String类型,完成格式化
        String format1 = sa.format(parse);
        System.out.println(format1);//2018年03月04日
//************************************************************************************************
        //1.用DateTimeFormatter的ofPattern静态方法,底层是有新建对象的,所以该方法结果就是创造了一个对象
        // public static DateTimeFormatter ofPattern(String pattern) {
        //        return new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter();
        //    }
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        //2.调用LocalDate(LocalDateTime/LocalTime)的parse(String,DateTimeFormatter)静态方法
        //将String类型转化为LocalDate(LocalDateTime/LocalTime)类型。完成解析
        LocalDate parse1 = LocalDate.parse(s, pattern);

        //1.用DateTimeFormatter的ofPattern静态方法,底层是有新建对象的,所以该方法结果就是创造了一个对象
        DateTimeFormatter pattern1 = DateTimeFormatter.ofPattern("yyyy年-MM月-dd日");
        //2.与simpleDateFormat不同的是,DateTimeFormatter对象没有format方法,用LocalDate的format(DateTimeFormatter)方法
        //,将LocalDate类型转化为String类型,完成格式化
        String format = parse1.format(pattern1);
        System.out.println(format);//2018年-03月-04日
    }
}

`
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值