Using DateFormat.getDateTimeInstance().format(date);

狂风中的少年 提交于 2019-12-23 07:04:19

问题


When running some tests I came across the following issue. When using:

private String printStandardDate(Date date) {
    return DateFormat.getDateTimeInstance(
        DateFormat.SHORT, DateFormat.SHORT).format(date);
}

I found this produced different formats of Date depending on the location the tests where run from. So locally in windows / eclipse I got a result: 04/02/12 18:18 but on the Linux box in America I get 2/4/12 6:18 PM

This causes my Tests/Build to fail:

expected:<[04/02/12 18:18]> but was:<[2/4/12 6:18 PM]>

Could anyone explain this behavior?


回答1:


That's not strange, that's exactly how it's supposed to work.

The API documentation of DateFormat.getDateTimeInstance says:

Gets the date/time formatter with the given date and time formatting styles for the default locale.

The default locale is different on your Windows system than on the Linux box in America.

If you want exact control over the date and time format, use SimpleDateFormat and specify the format yourself. For example:

private String printStandardDate(Date date) {
    return new SimpleDateFormat("dd/MM/yy HH:mm").format(date);
}

Even better would be to re-use the SimpleDateFormat object, but beware that it is not thread-safe (if the method might be called from multiple threads at the same time, things will get messed up if those threads use the same SimpleDateFormat object).

private static final DateFormat DATE_FORMAT =
    new SimpleDateFormat("dd/MM/yy HH:mm");

private String printStandardDate(Date date) {
    return DATE_FORMAT.format(date);
}



回答2:


The format is based on the default locale in your code. If you want to ensure results you must make sure to use a specific locale. The getDateTimeInstance method is overloaded to offer an alternative method that receives the locale that you want to use as parameter.

public static final DateFormat getDateTimeInstance(int dateStyle,
                             int timeStyle,
                             Locale aLocale)

If you use the same locale in both testing environments, the result should be the same.



来源:https://stackoverflow.com/questions/11312901/using-dateformat-getdatetimeinstance-formatdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!