Serjaru
Serjaru

Reputation: 87

Difference between two dates and TimeZone

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;

i expect res = "00:00:44.000" but res = "03:00:44.000"

Why g1 is 3 hour?

I think its TimeZone. But why? How to do it right?

Upvotes: 2

Views: 78

Answers (1)

Peter Alwin
Peter Alwin

Reputation: 239

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

You can set timezone to UTC format,

Upvotes: 1

Related Questions