使用DateFormat.getDateTimeInstance().format(date); [英] Using DateFormat.getDateTimeInstance().format(date);

查看:433
本文介绍了使用DateFormat.getDateTimeInstance().format(date);的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在运行一些测试时,我遇到了以下问题.使用时:

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

我发现这会产生不同格式的日期,具体取决于测试运行的位置.因此,在Windows/Eclipse本地,我得到了一个结果:04/02/12 18:18,但是在美国的Linux机器上,我得到了2/4/12 6:18 PM

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:

期望:< [[04/02/12 18:18]>,但是是:< [[2/4/12 6:18 PM]>

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

有人可以解释这种行为吗?

Could anyone explain this behavior?

推荐答案

这并不奇怪,这正是它应该工作的方式.

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

DateFormat.getDateTimeInstance的API文档说:

使用默认语言环境的获取具有给定日期和时间格式样式的日期/时间格式化程序.

在Windows系统上,默认语言环境与在美国的Linux系统上不同.

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

如果要精确控制日期和时间格式,请使用SimpleDateFormat并自行指定格式.例如:

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

更好的办法是重用SimpleDateFormat对象,但是要注意它不是线程安全的(如果可能同时从多个线程中调用该方法,那么如果这些线程使用相同的SimpleDateFormat对象).

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

这篇关于使用DateFormat.getDateTimeInstance().format(date);的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆