-2

我正在尝试将 UTC 日期/时间字符串转换为另一个时区。它仅显示 UTC 时区的日期/时间。

下面的代码:

        apiDate = "2013-04-16T16:05:50Z";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
        Date date = dateFormat.parse(apiDate);

        Calendar calendar = Calendar.getInstance();
        TimeZone timeZone = calendar.getTimeZone();

        SimpleDateFormat newDateFormat = new SimpleDateFormat("hh:mm aa, MMMM dd, yyyy");
        newDateFormat.setTimeZone(timeZone);
        String newDateString = newDateFormat.format(date);
4

2 回答 2

2

您应该将“解析”设置SimpleDateFormat为 UTC。否则,它实际上会在解析时假设您的默认时区:

TimeZone utc = TimeZone.getTimeZone("Etc/UTC");
dateFormat.setTimeZone(utc);

您也不需要构建日历来获取系统默认时区 - 只需使用:

TimeZone defaultZone = TimeZone.getDefault();
于 2013-04-15T14:07:28.647 回答
0
import java.util.Date;
import java.util.TimeZone;
import java.text.SimpleDateFormat;

public class Test {

    public static final SimpleDateFormat fDateTime = new SimpleDateFormat(
            "yyyy-MM-dd'T'HH:mm:ss");

    public static void main(String[] args) {

        String output = getFormattedDate("2016-03-1611T23:27:58+05:30");
        System.out.println(output);

    }

    public static String getFormattedDate(String inputDate) {

        try {
            Date dateAfterParsing = fDateTime.parse(inputDate);

            fDateTime.setTimeZone(TimeZone.getTimeZone("timeZone"));

            return fDateTime.format(dateAfterParsing);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
于 2016-03-28T10:18:34.463 回答