如何在Java中將字串格式化為dd-MM-yyyy格式的日期?


java.text 包提供了一個名為 SimpleDateFormat 的類,用於以所需的方式(本地)格式化和解析日期。

使用此類的方法,您可以將字串解析為日期或將日期格式化為字串。

將字串解析為日期

您可以使用 SimpleDateFormat 類的 parse() 方法將給定的字串解析為 Date 物件。您需要將日期以字串格式傳遞給此方法。要將字串解析為 Date 物件 -

  • 透過將日期的所需模式以字串格式傳遞給其建構函式來例項化 SimpleDateFormat 類。

//Instantiating the SimpleDateFormat class
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
  • 使用 parse() 方法透過將其作為引數傳遞來解析/轉換所需的字串為 Date 物件。

Date date = formatter.parse(dob);
System.out.println("Date object value: "+date);

示例

以下 Java 程式以字串格式接受使用者輸入的姓名和出生日期,將獲取的出生日期字串轉換為/解析為 Date 物件,並計算當前年齡並顯示結果。

 線上演示

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.Scanner;
public class CalculatingAge {
   public static Date StringToDate(String dob) throws ParseException{
      //Instantiating the SimpleDateFormat class
      SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
      //Parsing the given String to Date object
      Date date = formatter.parse(dob);
      System.out.println("Date object value: "+date);
      return date;
   }
   public static void main(String args[]) throws ParseException {
      //Reading name and date of birth from the user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your name: ");
      String name = sc.next();
      System.out.println("Enter your date of birth (dd-MM-yyyy): ");
      String dob = sc.next();
      //Converting String to Date
      Date date = CalculatingAge.StringToDate(dob);
      //Converting obtained Date object to LocalDate object
      Instant instant = date.toInstant();
      ZonedDateTime zone = instant.atZone(ZoneId.systemDefault());
      LocalDate givenDate = zone.toLocalDate();
      //Calculating the difference between given date to current date.
      Period period = Period.between(givenDate, LocalDate.now());
      System.out.print("Hello "+name+" your current age is: ");
      System.out.print(period.getYears()+" years "+period.getMonths()+" and "+period.getDays()+" days");
   }
}

輸出

Enter your name:
Krishna
Enter your date of birth (dd-MM-yyyy):
26-09-1989
Date object value: Tue Sep 26 00:00:00 IST 1989
Hello Krishna your current age is: 29 years 8 and 5 days

更新於: 2020年6月29日

16K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.