如何使用java.Time以某种格式打印时间戳

时间:2019-05-06 11:47:24

标签: java localization

我需要使用java.Time打印时间戳记,以en_US之类的语言环境表示:

Printed on 03/13/2019 at 20:04:03 (GMT+07:00) Bangkok, Hanoi, Jakarta.

1 个答案:

答案 0 :(得分:0)

我想以下代码可以满足您的要求。
您可以从下面的//When部分复制/粘贴代码。

import org.junit.Assert;
import org.junit.Test;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

import static java.time.ZonedDateTime.parse;

public class FormatDateTest {


    /**
     *  i need to print above using java.Time from country code like "en_US".
     *  Printed on 03/13/2019 at 20:04:03 (GMT+07:00) Bangkok, Hanoi, Jakarta.
     **/
    @Test
    public void format_shouldReturn() {
        // Given
        ZonedDateTime nowInUSA = parse("2019-03-13T09:04:03-05:00[America/New_York]");

        //When
        ZonedDateTime nowInGmtPlus7 = nowInUSA.withZoneSameInstant(ZoneId.ofOffset("GMT", ZoneOffset.of("+7")));
        String formattedDate = nowInGmtPlus7.format(DateTimeFormatter.ofPattern("MM/dd/yyyy"));
        String formattedTime = nowInGmtPlus7.format(DateTimeFormatter.ofPattern("HH:mm:ss (z)"));
        String message = String.format("Printed on %s at %s Bangkok, Hanoi, Jakarta.", formattedDate, formattedTime);

        //Then
        Assert.assertEquals("Printed on 03/13/2019 at 20:04:03 (GMT+07:00) Bangkok, Hanoi, Jakarta.",
                message);

    }