如何將字串中的日期解析成格式:dd/MM/yyyy 到 dd/MM/yyyy in java?


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

此類的建構函式之一接受一個表示所需日期格式的字串值,並構造 SimpleDateFormat 物件

此類的 format() 方法接受一個 java.util.Date 物件,並返回當前物件表示的格式中的日期/時間字串。

因此,若要解析日期字串到另一個日期格式 −

  • 獲取輸入日期字串。

  • 將其轉換為 java.util.Date 物件。

  • 透過將所需的(新)格式作為字串傳遞給其建構函式來例項化 SimpleDateFormat 類。

  • 透過將上述獲得的日期物件作為引數傳遞來呼叫 format() 方法。

示例

 動態演示

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class FormattingDate {
   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 = FormattingDate.StringToDate(dob);
      System.out.println("Select format: ");
      System.out.println("a: MM-dd-yyyy || b: dd-MM-yyyy || c: yyyy-MM-dd ");
      char ch = sc.next().toCharArray()[0];;
      switch (ch) {
         case 'a':
            System.out.println("Date in the format: MM-dd-yyyy");
            System.out.println(new SimpleDateFormat("MM-dd-yyyy").format(date));
            break;
         case 'b':
            System.out.println("Date in in the format: dd-MM-yyyy");
            System.out.println(new SimpleDateFormat("dd-MM-yyyy").format(date));
            break;
         case 'c':
            System.out.println("Date in the format: yyyy-MM-dd");
            System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(date));
            break;
         default:
            System.out.println("Model not found");
            break;
      }
   }
}

輸出

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
Select format:
a: MM-dd-yyyy || b: dd-MM-yyyy || c: yyyy-MM-dd
a
Date in the format: MM-dd-yyyy
09-26-1989

更新於:14-Oct-2019

1萬4千+ 瀏覽量

開啟你的職業

完成本課程獲得認證

開始學習
廣告
© . All rights reserved.