如何在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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP