有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

带有日期参数的java时区和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

<>我可能会尝试重写它,并创建自己的消息格式,考虑使用好的时区。但它可能不适合我们的架构

你还有其他选择吗


共 (1) 个答案

  1. # 1 楼答案

    我只是在看同样的问题。这个解决方案看起来很有趣: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中检查解析的格式,并将时区设置为日期格式