1

I have to convert a UTC date in this format "2016-09-25 17:26:12" to the current time zone of Android. I did this:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date myDate = simpleDateFormat.parse(temp.getString("date"));
System.out.println(mydate.toString());

This works but I don't know why it print also "GMT+02:00". This is the Output: "Sun Sep 25 19:26:12 GMT+02:00 2016", I don't want to show "GMT+02:00".

EDIT, CODE OF THE SOLUTION:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
SimpleDateFormat outputSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date myDate = simpleDateFormat.parse(temp.getString("date"));
System.out.println(outputSdf.format(myDate));
master94ga
  • 53
  • 2
  • 8

5 Answers5

3

tl;dr

LocalDateTime.parse( "2016-09-25 17:26:12".replace( " " , "T" ) )
             .atZoneSameInstant( ZoneId.systemDefault() )
             .format( DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM ) )

Avoid legacy date-time classes

You are using troublesome old date-time classes bundled with the earliest versions of Java. Now supplanted by the java.time classes.

ISO 8601

You input string nearly complies with the standard ISO 8601 format used by default with the java.time classes. Replace the SPACE in the middle with a T.

String input = "2016-09-25 17:26:12".replace( " " , "T" );

LocalDateTime

The input lacks any indication of offset-from-UTC or time zone. So we parse as a LocalDateTime.

LocalDateTime ldt = LocalDateTime.parse( input );

OffsetDateTime

You claim to know from the context of your app that this date-time value was intended to be UTC. So we assign that offset as the constant ZoneOffset.UTC to become a OffsetDateTime.

OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC );

ZonedDateTime

You also say you want to adjust this value into the current default time zone of the user’s JVM (or Android runtime in this case). Know that this default can change at any time during your app’s execution. If the time zone is critical, you should explicitly ask the user for a desired/expected time zone. The ZoneId class represents a time zone.

ZoneId z = ZoneId.systemDefault(); // Or, for example: ZoneId.of( "America/Montreal" )
ZonedDateTime zdt = odt.atZoneSameInstant( z );

Generate string

And you say you want to generate a string to represent this date-time value. You can specify any format you desire. But generally best to let java.time automatically localize for you according to the human language and cultural norms defined in a Locale object. Use FormatStyle to specify length or abbreviation (FULL, LONG, MEDIUM, SHORT).

Locale locale = Locale.getDefault();  // Or, for example: Locale.CANADA_FRENCH
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM ).withLocale( locale );
String output = zdt.format( f );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • My Project currently use java7, and it doesn't have some of the classes you used, I will try it after when I move the project to java8, thanks for the answer. – master94ga Sep 26 '16 at 11:34
  • @master94ga Re-read the second-to-last paragraph in my Answer, about [ThreeTen-Backport](http://www.threeten.org/threetenbp/) and [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP). – Basil Bourque Sep 26 '16 at 15:04
  • @BasilBourque (laugthing maniacally ...) thanks pal, you also suffered human idiocy named timezone hell and date format madness :) – Alex Sep 26 '16 at 20:48
2

it print GMT+02 because this is your "local" timezone. if you want to print the date without timezone information, use SimpleDateFormat to format the date to you liking.

edit : adding the code example (with your variable 'myDate')

SimpleDateFormat inputSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
inputSDF.setTimeZone(TimeZone.getTimeZone("UTC"));
Date myDate = inputSDF.parse("2016-09-25 17:26:12");
//
SimpleDateFormat outputSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(outputSDF.format(myDate));
System.out.println(TimeZone.getDefault().getID());

yield on the (my) console (with my local timezone).

2016-09-25 19:26:12
Europe/Paris
Alex
  • 189
  • 1
  • 7
  • Can you write the code please, I want the date to be in this format "yyyy-MM-dd HH:mm:ss" – master94ga Sep 25 '16 at 19:41
  • doing this the output is in UTC timezone and not in mine, also if I do `outputSdf.setTimeZone(TimeZone.getTimeZone("UTC"));` – master94ga Sep 25 '16 at 19:51
  • creating a SimpleDateFormat instance without invoking the setTimeZone method implie that the SDF instance will have the same TimeZone as your JVM System. showing that when you printed the myDate.toString() and it ended in "GMT+02:00" i can assure that the instance you should have created will have your local timezone by default. **that is unless you're reusing the one you created with UTC to do the parsing**. – Alex Sep 25 '16 at 19:58
  • thanks, my mistake was that I reused the instance created with UTC – master94ga Sep 25 '16 at 20:02
  • you're welcome, please note that the java Date object doesn't have a timezone "notion" so you should alvays use a SimpleDateFormat when you want to convert date 'point' to a timezoned human time representation (aka : formatted date :) ) – Alex Sep 25 '16 at 20:11
0

You can use :

system.out.println(myDate.getDay()+" "+myDate.getMonth()+" "+myDate.getYear());

Put what you need

Marwen Doukh
  • 1,946
  • 17
  • 26
  • 1
    This should work but I don't think is the best solution Edit: also the method you say are deprecated in Android – master94ga Sep 25 '16 at 19:36
0

You can do it with set timezone method.

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date myDate = simpleDateFormat.parse(rawQuestion.getString("AskDateTime"));
Gurjit Singh
  • 1,060
  • 2
  • 13
  • 16
0

Below is the toString() implementation of Date class:

public String toString() {
        // "EEE MMM dd HH:mm:ss zzz yyyy";
        BaseCalendar.Date date = normalize();
        StringBuilder sb = new StringBuilder(28);
        int index = date.getDayOfWeek();
        if (index == BaseCalendar.SUNDAY) {
            index = 8;
        }
        convertToAbbr(sb, wtb[index]).append(' ');                        // EEE
        convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' ');  // MMM
        CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd

        CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':');   // HH
        CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
        CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
        TimeZone zi = date.getZone();
        if (zi != null) {
            sb.append(zi.getDisplayName(date.isDaylightTime(), TimeZone.SHORT, Locale.US)); // zzz
        } else {
            sb.append("GMT");
        }
        sb.append(' ').append(date.getYear());  // yyyy
        return sb.toString();
    }

If you see, it appends Time zone info to the dates. If you don't want it to be printed, you can use SimpleDateFormat to convert Date to string, e.g.:

SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(format.format(new Date()));
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102