Atef Hares Atef Hares - 22 days ago 9
Android Question

Calendar getTimeInMillis returns same old value after chaneing date & time

I am converting String date and time to

Calendar
object

ex: 2015-09-05 16:30:20
this examples is not working: 2016-11-17 01:27:57


I am doing it like this

public static Calendar convert_String_Time_and_Date_To_Calendar(String time_and_date){
String TimeAndDate_array[] = time_and_date.split(" ");
String Date_details[]=TimeAndDate_array[0].split("-");
String Time_details[]=TimeAndDate_array[1].split(":");

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,Integer.parseInt(Date_details[0]));
calendar.set(Calendar.MONTH,Integer.parseInt(Date_details[1]));
calendar.set(Calendar.DAY_OF_MONTH,Integer.parseInt(Date_details[2]));

calendar.set(Calendar.HOUR_OF_DAY,Integer.parseInt(Time_details[0]));
calendar.set(Calendar.MINUTE,Integer.parseInt(Time_details[1]));
calendar.set(Calendar.SECOND,Integer.parseInt(Time_details[2]));

calendar.setTimeZone(TimeZone.getTimeZone("EET"));


return calendar;

}


and I am calling the method like this for ex:

Calendar today = Calendar.getInstance();
Calendar DandT = convert_String_Time_and_Date_To_Calendar("2015-09-05 16:30:20");
if(DandT.getTimeInMillis() < today.getTimeInMillis() ){
//do something
}else if(DandT.getTimeInMillis() == today.getTimeInMillis() ){
//do something
}


the problem is the
DandT
object is still having current day time in millis,
Actually while debugging I found that the at the method's return statement, the
calendar
object timeInMillis is the current time in mills even after calling
set()
although I checked the
calendar
object fields and found them changed !
So What is wrong ?

Answer

The month should be zero based :

calendar.set(Calendar.MONTH,Integer.parseInt(Date_details[1]) - 1);

You can also make the code shorter :

public static Calendar convert_String_Time_and_Date_To_Calendar(String time_and_date){
    SimpleDateFormat sdf = new SimpleDateFormat("yyy-mm-dd hh:mm");
    Date date = sdf.parse(time_and_date, 0);
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(date.getTime());
    return cal;
}