Java时间格式字符串与Date的相互转化


@


将Date转化为格式化字符串


将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


时间格式字符串转换为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();
      }

两点需要注意:

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



参考:

【1】:Java将字符串格式时间转化成Date格式
【2】:Java Review (二十一、基础类库----日期、时间类)
【3】:java8中文版-在线API

原文地址:https://www.cnblogs.com/three-fighter/p/12347262.html