[英]SimpleDateFormat Exception in Java
我是編程的初學者。
我希望我的代碼按照dd-MM-yyyy的格式進行格式化。
如果沒有拋出異常。
我需要做什么?
public Date(int day, int month, int year) {
this.Day = tag;
this.Month = month;
this.Year = year;
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
if (day != sdf) {
}
非常感謝你的幫助!
聽起來您應該使用LocalDate
類,這是Java 8存儲日和年的方式。 而且,由於您正在詢問格式化問題,因此我想您對使用DateTimeFormatter
並將其值作為String
返回感興趣。
public String formatDate(int day, int month, int year) {
LocalDate theDate = LocalDate.of(year, month, day);
DateTimeFormatter theFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
return theFormatter.format(theDate);
}
這會很有用
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Date1 {
public static void main(String args[]) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date strdate1 = sdf.parse("19-04-2018"); //target1 date
Date strdate2 = sdf.parse("02-04-2017"); //target2 date
if (strdate2.before(strdate1)) {
System.out.println("not outdated");
} else {
System.out.println("outdated");
}
} catch(ParseException ex) {
ex.printStackTrace();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.