I'm trying to set time to Calendar instance, but I'm experiencing weird behavior. Let's check some example:
Calendar c = Calendar.getInstance();
//c.setTime(date);
c.set(date.getYear(), (date.getMonth() - 1), date.getDay());
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
When I set time with setTime(), it sets wrong date. The second (and deprecated) set(year, month, day) works correctly. I've never met with this before - I thought that it uses default timezone in both cases, so it should be the same. Can someone explain it to me please?
==================== EDIT: Let's ask that another way:
Date date = new Date();
Calendar c1 = Calendar.getInstance();
c1.setTime(date);
Calendar c2 = Calendar.getInstance();
c2.set(date.getYear(), (date.getMonth() - 1), date.getDay());
int day1 = c1.get(Calendar.DAY_OF_WEEK);
int day2 = c2.get(Calendar.DAY_OF_WEEK);
// day1 != day2 ---> I'd like to know - WHY?
So for now are dates as follows:
date: Nov 5, 2013 4:27:02 PM
day1: 3
day2: 1
time: 1383665222638
timezone: Europe/Prague
This line does not do what you think it does:
c2.set(date.getYear(), (date.getMonth() - 1), date.getDay());
The deprecated methods in the Date
class work like this:
getYear()
returns year - 1900, so that for example 1986 is returned as 86, and 2013 is returned as 113.getMonth()
returns month - 1, so November is returned as 10. Subtracting 1 gives you October.getDay()
returns the day of the week; Tuesday is returned as 2.So, given your date, you are setting the calendar's date to Oct 2 year 113. The correct use of the API would be:
c2.set(1900+date.getYear(), date.getMonth(), date.getDate());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With