Java——时间日期格式化

时间格式化类

SimpleDateFormat类

抽象类,工厂方法。用于java.util.Date和java.sql.Date。线程不安全

参数
方法
方法
参数
返回值
参数
返回值
formatter = new SimpleDateFormat(pat)
yyyy年MM月dd日
.parse(strDate)
.format(Date)
formatter.parse(strDate)
formatter.format(Date)
字符串:2010年10月10日
对象:java.util.Date
对象:java.util.Date
字符串:2010年10月10日
  • 字符串格式化为时间对象

    .parse()方法

        // 从字符串提取出日期
        String strDate = "2008-11-17";
        String pat = "yyyy-MM-dd";
        SimpleDateFormat format2 = new SimpleDateFormat(pat);
        Date d = null;
        try {
            //生成时间对象
            d = format2.parse(strDate);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(format.format(d));
    
        //运行结果:Mon Nov 17 00:00:00 CST 2008
    
  • 时间对象格式化为字符串

    .format()方法

            // 将时间对象格式化为字符串
            Calendar cal = Calendar.getInstance();
            Date now = cal.getTime();
            SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
            String strDate = format.format(now);
            System.out.println(strDate);
    
            //运行结果:2019年06月20日
    

DateTimeFormatter类

java.time.format.DateTimeFormatter。用于java.time类中的时间日期格式化。线程安全

参数
参数
返回
参数
参数
返回
formatter=DateFormateter.ofPattern(pat)
yyyy年MM月dd日
LocalDate.parse(dateStr,formatter)
LocalDate date
formatter
'2016年11月11日'
(LocalDate)date.foramt(formatter)
formatter
'2016年11月11日'
  • 字符串转化为时间对象

    .parse()

        // 将字符串转化为时间
        String dateStr = "2016年10月25日";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        LocalDate date = LocalDate.parse(dateStr, formatter);
        System.out.println(date);
    
        //结果:2016-10-25
    
  • 时间对象格式化为字符串

    .format()

        // 将日期转化为字符串
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 hh:mm:ss");
        String nowStr = now.format(formatter2);
        System.out.println(nowStr);
    
        //j结果:2019年06月20日 04:38:41
    
  • 5
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值