两个日期和时区之间的差异

时间:2019-12-11 11:11:21

标签: java android

String s1 = "00:00:00.221";
String s2 = "00:00:44.221";

Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
Calendar c3 = Calendar.getInstance();

SimpleDateFormat myformat= new SimpleDateFormat("HH:mm:ss.SSS");

c1.setTime(myformat.parse(s1));
c2.setTime(myformat.parse(s2));

long mills= c2.getTimeInMillis() - c1.getTimeInMillis();

c3.setTimeInMillis(mills);

String g1 = String.valueOf(c3.get(Calendar.HOUR));
String g2 = String.valueOf(c3.get(Calendar.MINUTE));
String g3 = String.valueOf(c3.get(Calendar.SECOND));
String g4 = String.valueOf(c3.get(Calendar.MILLISECOND));
String res = g1 + ":" + g2 + ":" + g3 + "."+g4;

我希望 res =“ 00:00:44.000” res =“ 03:00:44.000”

为什么 g1 3 小时?

我认为它的时区。但为什么?怎么做对呢?

1 个答案:

答案 0 :(得分:1)

       try {
        String s1 = "00:00:00.221";
        String s2 = "00:00:44.221";
        SimpleDateFormat myformat = new SimpleDateFormat("hh:mm:ss.SSS", Locale.getDefault());
        Date date = myformat.parse(s1);
        Date date1 = myformat.parse(s2);

        long value = date1.getTime() - date.getTime();
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
        calendar.setTime(new Date(value));
        String g1 = String.valueOf(calendar.get(Calendar.HOUR));
        String g2 = String.valueOf(calendar.get(Calendar.MINUTE));
        String g3 = String.valueOf(calendar.get(Calendar.SECOND));
        String g4 = String.valueOf(calendar.get(Calendar.MILLISECOND));
        String res = g1 + ":" + g2 + ":" + g3 + "." + g4;
        Toast.makeText(this, res, Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        e.printStackTrace();
    }

您可以将时区设置为UTC格式,