zoukankan      html  css  js  c++  java
  • java 日期格式化

    DateFormat DateFormat 是日期/时间格式化子类的抽象类,它以与语言无关的方式格式化并解析日期或时间。

    SimpleDateFormat SimpleDateFormat 是一个以与语言环境有关的方式来格式化和解析日期的具体类。

    DateTimeFormatter 对 LocalDateTime进行格式化

    
    
    
    Date date = new Date();
    date.setYear(118);// 2018
    date.setMonth(8);// 9
    date.setDate(8);
    date.setHours(8);
    date.setMinutes(8);
    date.setSeconds(8);
    // d.setTime(1470230414353l);
    System.out.println(date);// Sat Sep 08 08:08:08 CST 2018

    DateFormat 

    String dateStr = DateFormat.getDateInstance().format(date);
    System.out.println(dateStr);// 2018-9-8
    
    dateStr = DateFormat.getDateInstance(DateFormat.DEFAULT).format(date);
    System.out.println(dateStr);// 2018-9-8
    
    dateStr = DateFormat.getDateInstance(DateFormat.FULL).format(date);
    System.out.println(dateStr);// 2018年9月8日 星期六
    
    dateStr = DateFormat.getDateInstance(DateFormat.MEDIUM).format(date);
    System.out.println(dateStr);// 2018-9-8
    
    dateStr = DateFormat.getDateInstance(DateFormat.SHORT).format(date);
    System.out.println(dateStr);// 18-9-8

    SimpleDateFormat

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    dateStr = format.format(date);
    System.out.println(dateStr);// 2018-09-08 20:08:08

    字符串解析为Date

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date endDate = sdf.parse("2018-08-08");
    System.out.println(endDate);//Wed Aug 08 00:00:00 CST 2018

    DateTimeFormatter 

    //利用DateTimeFormatter进行 LocalDateTime与String互转
    {//LocalDateTime转String(LocalDate,LocalTime类似)
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.now();
        String localDateTimeStr = dtf.format(localDateTime);
        System.out.println("LocalDateTime转成String类型的时间:" + localDateTimeStr);//2020-06-01 13:23:32
        System.out.println("LocalDateTime转成String类型的时间:" + localDateTime.toString());//2020-06-01T13:23:32.430
    }
    {//String转LocalDateTime(LocalDate,LocalTime类似)
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.parse("2018-06-01 10:12:05", dtf);
        System.out.println("String类型的时间转成LocalDateTime:" + localDateTime);//2018-06-01T10:12:05
    }

    日期和时间模式表达方法

    在使用SimpleDateFormat的时候,需要通过字母来描述时间元素,并组装成想要的日期和时间模式。常用的时间元素和字母的对应表如下:

    -w717

    模式字母通常是重复的,其数量确定其精确表示。如下表是常用的输出格式的表示方法。

    -w535

    注:

    200601 v1.3 增加DateTimeFormatter

  • 相关阅读:
    Hive 导入、导出数据
    mysql 命令行参数说明
    mysql 查看表信息
    python之冒泡排序
    python之选择排序
    python之快速排序
    光荣之路测试开发面试linux考题之四:性能命令
    测试开发linux面试之三:后台进程之操作
    测试开发面试的Linux面试题总结之二:常用命令
    测试开发面试的Linux面试题总结之一:vim使用方法
  • 原文地址:https://www.cnblogs.com/ooo0/p/9818431.html
Copyright © 2011-2022 走看看