Android时间问题

fis*_*h40 0 java android

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

    }

}
Run Code Online (Sandbox Code Playgroud)

在我的申请中,我正在与时间合作,我在这里有一些问题.看看下面我有这个结果.

list.get(0) = 03:00-03:06
temp1=2012/5/25 03:00
temp2=2012/5/25 03:06
Run Code Online (Sandbox Code Playgroud)

但是当我尝试这样做时

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());
Run Code Online (Sandbox Code Playgroud)

我有这个结果

Year=112
Month=4
Day=5
Hour=3
Minutes=0
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*eet 5

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

当然 - 您正在使用弃用的方法(您应该收到警告 - 不要忽略它们!),而您还没有阅读过它们的文档.例如,来自Date.getYear():

返回一个值,该值是从包含或以此Date对象表示的时刻开始的年份减去1900的结果,如本地时区中所解释的那样.

如果你想坚持使用JDK,你应该在适当的时区使用java.util.Calendar(用Datevia 填充它setTime).请注意,月份仍以0为基础Calendar,尽管年份至少更合理.

但是,如果可能的话,通常最好使用Joda Time.这是一个更好的深思熟虑的API.它可能太大了你想要在Android上使用它 - 你可能希望看看是否有可用的缩减版本.