-2

I'm trying get current time and then, convert to UTC+1 time zone which is in yyyy-MM-dd HH:mm:ss format

I tried the following code. It didn't work. Can anyone help?

public static String getDateTime() {
    Date time = Calendar.getInstance().getTime();
    SimpleDateFormat outputFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        
    outputFmt.setTimeZone(TimeZone.getTimeZone("UTC+1"));
    return outputFmt.format(time);
}
Jin
  • 21
  • 5
  • 1
    Possible duplicate of [Convert Date/Time for given Timezone - java](https://stackoverflow.com/questions/7670355/convert-date-time-for-given-timezone-java) – Robin Vinzenz Jun 27 '19 at 15:23
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. `OffsetDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"))`. – Ole V.V. Jun 29 '19 at 09:24
  • Possible duplicate of [How can I get the current date and time in UTC or GMT in Java?](https://stackoverflow.com/questions/308683/how-can-i-get-the-current-date-and-time-in-utc-or-gmt-in-java) – Ole V.V. Jun 29 '19 at 09:29

2 Answers2

0

I think you can try:

public static String getDateTime() { 

    SimpleDateFormat outputFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 

    // Read current time already in desired timezone
    Calendar time = Calendar.getInstance(TimeZone.getTimeZone("Europe/London")); 

    return outputFmt.format(time.getTime());
}
guipivoto
  • 18,327
  • 9
  • 60
  • 75
  • On my computer this just returned `2019-06-29 11:30:12`, which is the current time in my my time zone. So neither UTC nor Europe/London. – Ole V.V. Jun 29 '19 at 09:31
0

Following method will add one hour to UTC time.

public static String getDateTime()

{

SimpleDateFormat outputFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
outputFmt.setTimeZone(TimeZone.getTimeZone("UTC"));
String utctime=outputFmt.format(new Date());
String time=null;
Calendar calendar=null;
Date date;

try
{
    calendar = Calendar.getInstance();
    calendar.setTime(outputFmt.parse(utctime));
    calendar.add(Calendar.HOUR, 1);
    date=calendar.getTime();
    time=outputFmt.format(date);

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

return time;

}

Jin
  • 21
  • 5