soapergem
soapergem

Reputation: 10029

How do you format a time in UTC using FastDateFormat?

Here's a simple unit test to illustrate the problem I'm running into.

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

My computer is in Central Time, which means that when I run this code, the assertion fails because fdf formats the Date as 9 AM instead of 3 PM. How can I tell it format things in UTC instead?

Upvotes: 3

Views: 10141

Answers (1)

brso05
brso05

Reputation: 13232

Try doing this:

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

Upvotes: 7

Related Questions