Search code examples
androiddatetimeandroid-calendarandroid-date

dealing with Date and Time separately


I want to deal with date and time separately in my android app, by saying separately I mean setting the time without affecting the date and vice versa, So, when setting the time only:

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.YEAR + 1990, Calendar.MONTH, Calendar.DAY_OF_MONTH, hours, minutes, 0);

and it works perfectly, but when setting the Date only:

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new_date);

I face a problem of having the time set to 00:00:00, So, I tried to save the time values before and set the date the following way:

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new_date);
    calendar.set(Calendar.YEAR + 1990, Calendar.MONTH, Calendar.DAY_OF_MONTH, saved_hours, saved_minutes, 0);

But that makes the date saved as it's default value as (Calendar.YEAR||.MONTH||.DAY_OF_MONTH) returns the zero date values of the device which is a date in 1990's despite I'm excuting this command after setting the new Date.

Hint: Methods (mDate.getYear(), mDate.getMonth, .....etc) are deprecated.


Solution

  • To set date and time separately you can use this code

      Calendar cal = Calendar.getInstance();
        // Note: Months value is MonthNumber-1 (Jan is 0, Feb is 1 and so on).
        cal.set(Calendar.MONTH, 9);
        cal.set(Calendar.DATE, 24);
        cal.set(Calendar.YEAR, 2013);
        cal.set(Calendar.HOUR,1);         // when wanting to set it as 12 Hour system
        cal.set(Calendar.HOUR_OF_DAY,13); // when wanting to set it as 24 Hour system
        cal.set(Calendar.MINUTE,45);
        cal.set(Calendar.SECOND,52);
    
      // set the year,month and day to something else
      //set(int year,int month,int day)
      cal.set(1995, 5, 25);
    
    
    // set(int year,int month,int day,int hourOfDay, int minute,int second)
       cal.set(1995, 5, 25, 04, 15, 20);