I passed the test with this code but in the Conditions example it returns "true" for January 1 2000. My code returns "false".
I am confused again. Did I solve the task right or not?
public class Solution {
public static void main(String[] args) throws ParseException {
System.out.println(isDateOdd("JANUARY 1 2000"));
}
public static boolean isDateOdd(String date) throws ParseException {
boolean odd = true;
SimpleDateFormat format = new SimpleDateFormat("MMMMM dd yyyy", Locale.ENGLISH);
Date parsedTime = format.parse(date);
Date yearStartTime = new Date();
int year = parsedTime.getYear();
yearStartTime.setYear(year);
yearStartTime.setHours(0);
yearStartTime.setMinutes(0);
yearStartTime.setSeconds(0);
yearStartTime.setDate(1);
yearStartTime.setMonth(0);
long a = parsedTime.getTime() - yearStartTime.getTime();
long b = a/(1000*60*60*24);
if(b % 2 == 0){
odd = false;
}
else if(b % 2 != 0){
odd = true;
}
return odd;
}
}
OUTPUT:
false
passed testing, but wrong output
Resolved
Comments (4)
- Popular
- New
- Old
You must be signed in to leave a comment
Nouser
23 January 2021, 19:40solution
I give you some hints why it failed. Why it passed I can not tell you ;)
Here you save the current time in millis. Then you set all possible values to the 1st of January at 00:00:00. The problem is, that there are still the millis. So when you subtract the start time from the passed date, you also subtract the millis from that passed date, eg. 377. So long a results in -377, b is -377/ (1000*60*60*24) and your modulo operation gives totally random values (dependent on when the new Date() command gets executed). +1
Jurij Thmsn
24 January 2021, 09:08
Thanks a lot, Nouser! I would never have found this out by myself. Still puzzled why it passed validation :D but thats just secondary.
I tried to find out how to set the milliseconds to zero but it seems not possible with date!? I guess I should have used the Calendar class, it has a method for setting the milliseconds.
Thanks!
0
Nouser
24 January 2021, 14:15useful
Calendar has a didicated method for that purpose ;)
And to get rid of the ms you could just divide them out. / 1000 and then again * 1000
+1
Jurij Thmsn
24 January 2021, 16:55
I'll try that. Thanks again :)
0