如何使用 FastDateFormat 以 UTC 格式格式化时间?

soa*_*gem 3 java date apache-commons simpledateformat

这是一个简单的单元测试来说明我遇到的问题。

package mytest;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import org.apache.commons.lang3.time.FastDateFormat;
import org.junit.Test;

import static org.junit.Assert.*;

public class DateTests {

    private static final String DATE_VALUE = "2016-03-11T15:47:02.123Z";
    private static final String PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";

    @Test
    public void utcTest() throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat(PATTERN);
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date date = sdf.parse(DATE_VALUE)

        FastDateFormat fdf = FastDateFormat.getInstance(PATTERN);
        assertEquals(DATE_VALUE, fdf.format(date));
    }
}
Run Code Online (Sandbox Code Playgroud)

我的计算机处于中部时间,这意味着当我运行此代码时,断言失败,因为fdf将日期格式化为上午 9 点而不是下午 3 点。我怎么能告诉它在 UTC 中格式化东西呢?

brs*_*o05 5

尝试这样做:

FastDateFormat fdf = FastDateFormat.getInstance(PATTERN, TimeZone.getTimeZone("UTC"));
Run Code Online (Sandbox Code Playgroud)