带有日期参数的TimeZone和MessageFormat [英] TimeZone and MessageFormat with date parameters

查看:55
本文介绍了带有日期参数的TimeZone和MessageFormat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

MessageFormat class is cool because we can insert parameters and do the formatting directly with it. This permits me to be able to easily override a date format directly in a message bundle properties files.

例如:

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

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

But what if i need to display the date in different timezones?

我知道我可以在将所有日期注入到我的捆绑包中之前格式化所有日期,但这很难格式化显示的每个日期...

I know i can format all dates before injecting them in my bundle, but this is a pain to format every date displayed...

在工作中,我们使用

org.springframework.context.support.ReloadableResourceBundleMessageSource

org.springframework.context.support.ReloadableResourceBundleMessageSource

我可能可以尝试覆盖它,并创建自己的MessageFormat,以考虑使用合适的时区.但这可能不适合我们的体系结构.

I can probably try to override it and create my own MessageFormat that would consider using the good timezone. But it may not fit well for our architecture.

您还有其他选择吗?

推荐答案

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

I was just looking at the same problem. This solution looks interesting: 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设置为日期格式.

Idea is to go over parsed formats in MessageFormat, and set TimeZone to date formats.

这篇关于带有日期参数的TimeZone和MessageFormat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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