Convert UTC date to current timezone

前端 未结 5 1144
广开言路
广开言路 2021-01-27 02:51

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 Simp         


        
相关标签:
5条回答
  • 2021-01-27 03:14

    You can use :

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

    Put what you need

    0 讨论(0)
  • 2021-01-27 03:18

    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"));
    
    0 讨论(0)
  • 2021-01-27 03:25

    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.

    0 讨论(0)
  • 2021-01-27 03:28

    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
    
    0 讨论(0)
  • 2021-01-27 03:33

    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()));
    
    0 讨论(0)
提交回复
热议问题