Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calendar set() method not setting proper time

Tags:

java

I'm setting the time on my calendar instance as following

private Calendar mCalendar = Calendar.getInstance();

public void onTimeSet(int hourOfDay, int minute, int second) {
    int year = mCalendar.get(Calendar.YEAR);
    int monthOfYear = mCalendar.get(Calendar.MONTH);
    int dayOfMonth = mCalendar.get(Calendar.DAY_OF_MONTH);

    Calendar lCalendar = Calendar.getInstance();
    lCalendar.set(year, monthOfYear, dayOfMonth, hourOfDay, minute);

    Date lDate = lCalendar.getTime();
    if (lDate.before(new Date())) {
        return;
    } else {
        mCalendar.set(year, monthOfYear, dayOfMonth, hourOfDay, minute);
        setItemTime();
    }
}

However, on call to getTime() on both the instances of Calendar lCalendar and mCalendar, I'm getting the time at which the Calendar was instantiated not from the hourOfDay and minute arguments set on calendar instances. Also, if I call getTime() method again on the either instances I get the correct time.

Why is this happening and how can I solve this?

like image 269
Harry Avatar asked Oct 31 '22 10:10

Harry


1 Answers

Go through Section , Field Manipulation at Calendar Documentation

Basically, you are setting fields not time and trying to get time but not individual set fields. As per documentation, Calendar time is not immediately updated after calling set(...) functions.

There, Read between the lines that ,

The specifics are determined by the concrete calendar class.

So I guess, universal answer can't be provided.

like image 184
Sabir Khan Avatar answered Nov 12 '22 22:11

Sabir Khan