2012-06-25 45 views
0
private void getSelectedTime(final String json){ 

     Calendar now = Calendar.getInstance(); 
     int year = now.get(Calendar.YEAR); 
     int month = now.get(Calendar.MONTH); // Note: zero based! 
     int day = now.get(Calendar.DAY_OF_MONTH); 
     int hour = now.get(Calendar.HOUR_OF_DAY); 
     int minute = now.get(Calendar.MINUTE); 
     int second = now.get(Calendar.SECOND); 
     int millis = now.get(Calendar.MILLISECOND); 
     SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm"); 


     JSONArray list; 
     JSONObject jsonObject; 

     try { 
      jsonObject = new JSONObject(json); 

      list = jsonObject.getJSONArray("3"); 
      StringTokenizer tokenizer = new StringTokenizer(list.get(0).toString(),"-"); 
      String startTime = tokenizer.nextToken(); 
      String endTime = tokenizer.nextToken(); 
      String temp1 = year+"/"+month+"/"+day+" "+startTime; 
      String temp2 = year+"/"+month+"/"+day+" "+endTime; 
      System.out.println("temp1="+temp1); 
      System.out.println("temp2="+temp2); 

      Date date1 = dateFormat.parse(temp1); // temp1=2012/5/25 03:00 
      Date date2 = dateFormat.parse(temp2); //temp2=2012/5/25 03:06 

      System.out.println("Year1="+date1.getYear()); 
      System.out.println("Month1="+date1.getMonth()); 
      System.out.println("Day1="+date1.getDay()); 
      System.out.println("Hour1="+date1.getHours()); 
      System.out.println("Minutes1="+date1.getMinutes()); 

     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     catch (ParseException e) { 
      e.printStackTrace(); 
     } 

    } 

} 

在我的应用程序中,我正在与时间和我在这里有一些问题。看看下面我有这个结果。Android时间问题

list.get(0) = 03:00-03:06 
temp1=2012/5/25 03:00 
temp2=2012/5/25 03:06 

但是,当我试图做到这一点

System.out.println("Year="+date1.getYear()); 
System.out.println("Month="+date1.getMonth()); 
System.out.println("Day="+date1.getDay()); 
System.out.println("Hour="+date1.getHours()); 
System.out.println("Minutes="+date1.getMinutes()); 

我有这样的结果

Year=112 
Month=4 
Day=5 
Hour=3 
Minutes=0 

谁能告诉我为什么结果是错误的?

回答

5

谁能告诉我为什么我的结果是错误的?

当然 - 你正在使用不推荐的方法(你应该得到警告 - 不要忽略它们!),你还没有阅读他们的文档。例如,从Date.getYear()

返回一个值,是从包含或开始于此Date对象表示,作为本地时区进行解释时的瞬间开始的年份减去1900的结果。

如果你想坚持的JDK,你应该使用java.util.Calendar,而不是在适当的时区(与Date通过setTime填充它)。请注意,Calendar的月份仍以0为基础,尽管年份至少比较明智。

但是,如果可能的话,使用Joda Time通常会更好。这是一个更好的思想API。虽然您可能想要在Android上使用它,但可能太大了 - 您可能希望看看是否有可用的缩减版本。

+0

哇,我应该用什么来代替日期? – fish40

+0

@ fish40:查看我编辑的答案,或阅读废弃警告的文档。 –

+0

非常感谢您的回复 – fish40

0

你也可以做的,而不是date1.getYear()

Calendar cal = Calendar.getInstance(); 
cal.setTime(date1); 

int year = cal.get(Calendar.year); 

这也适用于其他时间值。 或者您可以使用已建议的Joda时间。