有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用FastDateFormat设置UTC时间格式?

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

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

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


共 (1) 个答案

  1. # 1 楼答案

    尝试这样做:

    FastDateFormat fdf = FastDateFormat.getInstance(PATTERN, TimeZone.getTimeZone("UTC"));