java.text 套件提供了一個名為 SimpleDateFormat 的類,用於以所需的方式(本地)格式化和解析日期。
此類的建構子之一接受表示所需日期格式的字串值和建構子 SimpleDateFormat 物件。
此類的format() 方法接受 java.util.Date 物件並傳回目前物件表示的格式的日期/時間字符串。
因此,將日期字串解析為另一種日期格式 -
取得輸入的日期字串。
-
將其轉換為 java.util.Date 物件。
> 透過將所需的(新)格式作為字串傳遞給其建構函式來實例化 SimpleDateFormat 類別。
透過以下方式呼叫 format() 方法:將上面取得的 Date 物件作為參數傳遞。
範例
現場示範
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
以上是如何在Java中將格式為dd/MM/yyyy的字串解析為dd/MM/yyyy的日期?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本文討論了使用Maven和Gradle進行Java項目管理,構建自動化和依賴性解決方案,以比較其方法和優化策略。

本文使用Maven和Gradle之類的工具討論了具有適當的版本控制和依賴關係管理的自定義Java庫(JAR文件)的創建和使用。

本文討論了使用咖啡因和Guava緩存在Java中實施多層緩存以提高應用程序性能。它涵蓋設置,集成和績效優勢,以及配置和驅逐政策管理最佳PRA

本文討論了使用JPA進行對象相關映射,並具有高級功能,例如緩存和懶惰加載。它涵蓋了設置,實體映射和優化性能的最佳實踐,同時突出潛在的陷阱。[159個字符]

Java的類上載涉及使用帶有引導,擴展程序和應用程序類負載器的分層系統加載,鏈接和初始化類。父代授權模型確保首先加載核心類別,從而影響自定義類LOA


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

禪工作室 13.0.1
強大的PHP整合開發環境

SublimeText3漢化版
中文版,非常好用

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!