如何在 Java 中将日期格式化为字符串?


java.text 包提供的一个名为 SimpleDateFormat 的类,用于按照所需的方式(本地)格式化和解析日期。

使用此类的这些方法,可以将字符串解析为日期,或将日期格式化为字符串。

将日期格式化为字符串

可以使用 SimpleDateFormat 类的 parse() 方法将给定的字符串格式化为日期对象。此方法需要传入字符串格式的日期。将字符串格式化为日期对象 -

  • 通过将所需日期模式(字符串格式)作为参数传递给其构造函数,实例化 SimpleDateFormat 类。

//Instantiating the SimpleDateFormat class
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
  • 通过将所需日期对象作为参数传递给 format() 方法,格式化/转换日期对象为字符串。

//Formatting the obtained date
String formattedDate = formatter.format(date);

示例

以下 Java 程序将当前日期格式化为字符串并打印。

 在线演示

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
public class DateToString {
   public static void main(String args[]) throws ParseException {
      //Retrieving the current date
      LocalDate localDate = LocalDate.now();
      //Converting LocalDate object to Date
      Date date = java.sql.Date.valueOf(localDate);
      //Instantiating the SimpleDateFormat class
      SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
      //Formatting the obtained date
      String formattedDate = formatter.format(date);
      System.out.println("Formatted date: "+formattedDate);
   }
}

输出

Formatted date: 31-05-2019

更新日期:2020 年 06 月 29 日

2K+ 浏览量

开启您的 职业生涯

完成课程以获得认证

开始
广告
© . All rights reserved.