SimpleDateFormat在给定日期返回不正确的日期 [英] SimpleDateFormat returning incorrect day on given date
问题描述
我最近在HackerRank上提问,要求我查找给定日期的日期.我用 SimpleDateFormat
查找日期.
I was recently doing a question on HackerRank in which I was asked to find the day on a given date. I used SimpleDateFormat
to find the day.
下面是我的代码:
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( Friday
),但是它在2015年5月8日返回了错误的日期(应该返回星期三
,但返回 Monday
).
The funny thing here is that the above code is printing correct result for today's date i.e. 03/04/2020(Friday
) but it is returning incorrect day on 05/08/2015(it should return Wednesday
but instead it returns Monday
).
请帮助我发现问题.
谢谢.
编辑我在犯一个小错误,因为我想使用每月的某天,因此必须使用 dd
. DD
代表一年中的一天.那解决了我的问题!
EDIT
I was doing a little mistake that I wanted to use the day of the month, for which dd
has to be used. DD
represents the day of the year. That solved my problem!
推荐答案
您应该使用 SimpleDateFormat("dd-MM-yyyy")
.
DD是一年中的某天,例如一年中有365天.
DD is for day in year, like there are 365 days in a year.
这篇关于SimpleDateFormat在给定日期返回不正确的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!