Convert UTC date to current timezone

前端 未结 5 1182
广开言路
广开言路 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条回答
  •  Happy的楠姐
    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()));
    

提交回复
热议问题