java - 带有日期参数的 TimeZone 和 MessageFormat

标签 java spring date-format simpledateformat messageformat

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

例如:

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

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

我知道我可以在将所有日期注入(inject)我的包之前格式化所有日期,但是格式化每个显示的日期是一件痛苦的事情...


在工作中我们正在使用

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

关于java - 带有日期参数的 TimeZone 和 MessageFormat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11610802/

相关文章:

java - 运行jar时出现找不到元素声明 'beans'错误

java - 使用日期格式验证日期

java - 俄语语言环境中的日期解析问题

java - Spring MVC : how to intercept 404 before returning error page/response?

java - 如何在我的表单中插入时间的 PHP 代码?

java - H2用户自定义函数被多次调用

java - 在 2.3.4 中序列化 DecimalFormatSymbols 时出现问题

java - 如果 String 包含 Char[] 数组,则用于在 String 中搜索的代码?

java - 将 spring boot 部署到 weblogic 10.3 时出错 - AppMerge 流的进程中的异常

hibernate - "Transaction in view"与 Hibernate、Spring、Struts