天天看点

Java时间格式字符串与Date的相互转化将Date转化为格式化字符串时间格式字符串转化为DateJava8新的时间API

文章目录

将Date转化为格式化字符串是利用SimpleDateFormat类继承自 java.text.DateFormat类的format方法实现的:

  • public final String format(Date date):将日期格式化成日期/时间字符串。
//获取当前时间
        Date date = new Date();
       //定义转化为字符串的日期格式 
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //将时间转化为类似 2020-02-13 16:01:30 格式的字符串
        String d=sdf.format(date);      

时间格式字符串转换为Date是利用SimpleDateFormat类继承自 java.text.DateFormat类的Parse方法实现的:

  • public Date parse(String source) throws ParseException:从给定字符串的开始解析文本以生成日期。 该方法可能不会使用给定字符串的整个文本。
String time = "2020-02-13 16:01:30";
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  Date date = null;
  try {
        date = sdf.parse(time);
      } catch (ParseException e) {
        e.printStackTrace();
      }      

两点需要注意:

  • 字符串要和定义的格式一致
  • 要作异常处理

Java旧的时间API饱受诟病,Java8以后提供了新的时间API,在java.time包下。

//获取当前时间
        LocalDateTime date=LocalDateTime.now();
        //创建日期时间对象格式化器,日期格式类似: 2020-02-23 22:18:38
        DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //将时间转化为对应格式的字符串
        String fomateDate=date.format(formatter).toString();      

//创建日期时间对象格式化器,日期格式类似: 2020-02-23 22:18:38
        DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //时间格式字符串
        String sDate="2020-02-23 22:18:38";
        //将时间格式字符串转化为LocalDateTime对象,需传入日期对象格式化器
        LocalDateTime parseDate=LocalDateTime.parse(sDate,formatter);      

这里也需要需要注意格式化器的格式和字符串的格式要一致。