加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

带有日期参数的TimeZone和MessageFormat

发布时间:2020-12-15 01:45:57 所属栏目:大数据 来源:网络整理
导读:MessageFormat类很酷,因为我们可以插入参数并直接使用它进行格式化. 这使我能够直接在消息包属性文件中轻松覆盖日期格式. 举个例子: MessageFormat.format("Test inserting a date param here: {0,date,dd/MM/yyyy HH'h'mm} - OK cool",new Date() ); 但是,

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设置为日期格式.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读