Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting time for calendar instance

Tags:

java

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
like image 362
shmoula Avatar asked Dec 20 '22 22:12

shmoula


1 Answers

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());
like image 194
Joni Avatar answered Jan 05 '23 15:01

Joni