微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

带有日期参数的TimeZone和MessageFormat

messageformat类很酷,因为我们可以插入参数并直接使用它进行格式化.
这使我能够直接在消息包属性文件中轻松覆盖日期格式.

举个例子:

messageformat.format("Test inserting a date param here: {0,date,dd/MM/yyyy HH'h'mm} -> OK cool",new Date() );

但是,如果我需要在不同的时区显示日期怎么办?

我知道我可以在将它们注入我的包中之前格式化所有日期,但是格式化每个显示的日期都很麻烦…

在工作中我们正在使用

org.springframework.context.support.ReloadableResourceBundleMessageSource

我可能会尝试覆盖它并创建我自己的messageformat,它会考虑使用好的时区.但它可能不适合我们的架构.

你还有其他选择吗?

最佳答案
我只是在看同样的问题.这个解决方案看起来很有趣:https://groups.google.com/d/msg/comp.lang.java.programmer/1AJIpwtn5HA/zd3Sw8IJrTQJ

public class Format {
  public static void main(String argv[]) {
    messageformat mf = new messageformat("The time is: {0,time,HH:mm}");


    TimeZone tz = TimeZone.getTimeZone("GMT");
    Object [] formats = mf.getFormats();
    for (int i = 0; i < formats.length; i++) {
        if (formats[i] instanceof SimpleDateFormat) {
            ((SimpleDateFormat)formats[i]).setTimeZone(tz);
        }
    }
    Date date = new Date();
    Object [] args = {date};
    System.out.println(mf.format(args));
  }
}

想法是在messageformat中检查已解析的格式,并将TimeZone设置为日期格式.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐