java.text 包提供了一个名为 SimpleDateFormat 的类,用于以所需的方式(本地)格式化和解析日期。
此类的构造函数之一接受表示所需日期格式的字符串值和构造函数 SimpleDateFormat 对象。
此类的 format() 方法接受 java.util.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的日期?的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。