如何在 Java 中从年、月和日获取日期?
使用 of() 方法
java.time.LocalDate 类的 of() 方法接受年、月和日作为参数,创建并返回一个 LocalDate 对象。
示例
import java.time.LocalDate;
public class Test {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2014, 9, 11);
System.out.println("Date Value: "+date);
}
}输出
Date Value: 2014-09-11
使用 GregorianCalendar 类
java.util.GregorianCalendar 类的一个构造器接受年、月和日作为值,并创建一个表示它的 Calendar 对象。
示例
import java.util.*;
class Test {
public static void main(String args[]){
//Creating a calendar object
Calendar cal = new GregorianCalendar(2020, 07, 18);
int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
System.out.println("Day: " + day);
System.out.println("Month: " + month);
System.out.println("Year: " + year);
}
}输出
Day: 18 Month: 7 Year: 2020
使用 SimpleDateFormat 对象
此类的构造器之一接受一个表示所需日期格式的字符串值,并创建一个**SimpleDateFormat 对象。**要将字符串解析/转换为日期对象?-
- 通过传递所需格式字符串来实例化此类。
- 使用 parse() 方法解析日期字符串。
示例
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Sample {
public static void main(String args[]) throws ParseException {
String date_string = "2007-25-06";
//Instantiating the SimpleDateFormat class
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-dd-MM");
//Parsing the given String to Date object
Date date = formatter.parse(date_string);
System.out.println("Date value: "+date);
}
}输出
Date value: Mon Jun 25 00:00:00 IST 2007
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP