-1

I have two methods for get UTC date time.

method:1) get current UTC

 public static String getUTCdatetimeAsString()
{


    final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd- HH:mm:ss", Locale.US);
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    final String utcTime = sdf.format(new Date());
    Log.e("utcTime : " ,""+ utcTime);
    return utcTime;
}

which print below Log

utcTime : 2018-07-12- 12:37:09

method:2) select date from calendar and get UTC

public static String dateUTCToLocal() {

    try {
        SimpleDateFormat formatter = new SimpleDateFormat("d/M/yyyy HH:mm:ss", Locale.US);
        formatter.setTimeZone(TimeZone.getTimeZone("UTC"));

        Date value = formatter.parse("12/7/2018 06:07:09");

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd- HH:mm:ss", Locale.US);
        format.setTimeZone(TimeZone.getDefault());
        return format.format(value);

    } catch (ParseException e) {
        e.printStackTrace();
        return null;
    }
}

which print below Log

2018-07-12- 11:37:09

Problem : getting different UTC date (1 hour different )not understand why i tried many solutions but not getting perfect result, any help appreciate thanks in advance.

Mr. Ad
  • 333
  • 3
  • 12
  • As an aside consider throwing away the `Date` and `SimpleDateFormat` classes. They are long outdated, and the latter in particular notoriously troublesome. You’re far from the first having problems with it. Instead you may add [the ThreeTenABP library](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). It’s so much nicer to work with. – Ole V.V. Jul 12 '18 at 18:45
  • Was method 2 supposed to convert 12/7/2018 06:07:09 from UTC to local time or from local time to UTC? – Ole V.V. Jul 12 '18 at 19:27
  • Did you search thoroughly enough before asking? This question has been asked and answered many times already, so please do. Possible duplicate of [convert date and time in any timezone to UTC zone](https://stackoverflow.com/questions/24240896/convert-date-and-time-in-any-timezone-to-utc-zone). – Ole V.V. Jul 13 '18 at 08:50

2 Answers2

1

Try this format ..

 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd- HH:mm:ss a", Locale.US);

it show time into am pm wise.

0

The line "format.setTimeZone(TimeZone.getDefault());" sets the timezone you are currently in while "sdf.setTimeZone(TimeZone.getTimeZone("UTC"));" sets the timezone to "UTC". You should stick with the second line if you want to get UTC-time

MrGlue
  • 28
  • 5