我最近在hackerrank上问了一个问题,要求我在给定日期查找日期。我用SimpleDateFormat查找日期。下面是我的代码:
String sd = Integer.toString(day)+"-"+Integer.toString(month)+"-"+Integer.toString(year);
try{Date d = new SimpleDateFormat("DD-MM-yyyy").parse(sd);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
return sdf.format(d).toUpperCase();}
catch(Exception e){
return "";
}
[有趣的是,上面的代码为今天的日期(即03/04/2020(星期五))打印了正确的结果,但是它在2015年5月8日返回了错误的日期(应该返回星期三,但返回的是星期一) 。请帮助我发现问题。谢谢。
您应该使用SimpleDateFormat("dd-MM-yyyy")
。
DD是一年中的某天,例如一年中有365天。
执行以下操作:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.TextStyle;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
int day = 5;
int month = 8;
int year = 2010;
LocalDate date = LocalDate.of(year, month, day);
System.out.println(date.getDayOfWeek());
DayOfWeek dayOfWeek = date.getDayOfWeek();
System.out.println(dayOfWeek.getDisplayName(TextStyle.FULL, Locale.US));
System.out.println(dayOfWeek.getDisplayName(TextStyle.SHORT, Locale.US));
}
}
输出:
THURSDAY
Thursday
Thu