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

  • 相关阅读:
    matlab中的开方sqrt用牛顿迭代法实现的代码
    转载 迭代算法实现开平方
    关于verilog中小数直接赋值
    关于verilog中的signed类型
    第二十五篇:使用 sigaction 函数实现可靠信号
    第二十四篇:可靠信号机制
    第二十三篇:信号机制的两个思考
    第二十二篇:信号的接收和处理
    hdu 2918(IDA*)
    hdu 1813(IDA*)
  • 原文地址:https://www.cnblogs.com/ooo0/p/9818431.html
Copyright © 2011-2022 走看看