TimeZone and MessageFormat with date parameters

坚强是说给别人听的谎言 提交于 2021-01-27 04:46:07

问题


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.

For exemple:

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...


At work we are using

org.springframework.context.support.ReloadableResourceBundleMessageSource

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.

Do you see any other alternative?


回答1:


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

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



来源:https://stackoverflow.com/questions/11610802/timezone-and-messageformat-with-date-parameters

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