日历getTimeInMillis在chaneing date&之后返回相同的旧值。时间

时间:2016-11-18 15:59:49

标签: android calendar

我正在将字符串日期和时间转换为Calendar对象

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

我这样做

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;

}

我正在调用这样的方法,例如:

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
}

问题是DandT对象仍然以毫秒为单位的当前时间, 实际上在调试时我发现在方法的return语句中,calendar对象timeInMillis即使在调用set()之后也是磨机中的当前时间,尽管我检查了calendar个对象字段并发现他们改变了! 那有什么不对?

1 个答案:

答案 0 :(得分:1)

月份应为零:

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

您还可以缩短代码:

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;
}