简体   繁体   中英

Convert UTC date to current timezone

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

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

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 .

You can use :

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

Put what you need

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"));

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, eg:

SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(format.format(new Date()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM