【问题标题】:Whats the difference in using a and aaa in SimpleDateFormat在 SimpleDateFormat 中使用 a 和 aaa 有什么区别
【发布时间】:2011-05-05 06:01:15
【问题描述】:

我想将当前日期显示为00:50:32 A

这是我的代码

Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss a");
String time = sdf.format(date);
System.out.println("time : " + time);

但它打印为:

time : 00:50:32 AM

HH:mm:ss aHH:mm:ss aaa 我都试过了,但结果是一样的。

【问题讨论】:

    标签: java datetime formatting simpledateformat


    【解决方案1】:

    不能!如果模式为 4 个字母或更少,则使用短格式。所以 'a'、'aa'、'aaa' 和 'aaaa' 是相同的。

    您所能做的就是将其格式化为不带“a”的格式,然后手动添加“A”或“P”。

    话虽如此,使用“HH”(24 小时制)为什么需要上午/下午?

    【讨论】:

      【解决方案2】:

      我相信对于上午/下午标记,“短”和“长”之间没有区别。

      特别是,DateFormatSymbols.getAmPmStrings() 只返回两个字符串 - 并且没有 getShortAmPmStrings() 调用或类似的调用。

      【讨论】:

      • 注意还有 setAmPmStrings() ;-) 可以让系统中其他代码的生活变得有趣!
      • @road: 是的,Java 日期/时间 API 中普遍存在的可变性是可怕的 :(
      【解决方案3】:

      引用Javadoc of SimpleDateFormat:

      对于格式化,如果数量 图案字母为 4 个或更多,完整 使用表格;否则短或 如果可用,则使用缩写形式

      因此: (a) 如果您希望看到差异,请使用 aaaa (4 x a) 而不是 aaa (4 x a)。 (b) 鉴于 AM/PM 没有短格式(或长格式),那么对于 a 说明符,重复次数无关紧要。

      为了更彻底一点,我运行了以下程序。它发现格式受到影响的情况为零。

      Date date = new Date();
      int n = 0;
      for (String country : Locale.getISOCountries()) {
        for (String language : Locale.getISOLanguages()) {
          Locale loc = new Locale(language, country);
          String as = "";
          String prev = null;
          for (int i = 0; i < 20; ++i) {
            ++n;
            as += "a";
            String current = new SimpleDateFormat(as, loc).format(date);
            if (prev != null && !prev.equals(current)) {
              System.out.println("Locale: " + loc + ", as=" + as + ", current="
                + prev + ", next=" + current);
            }
      
            prev = current;
          }
        }
      }
      System.out.println("Tried out " + n + " combinations.");    
      

      【讨论】:

        【解决方案4】:

        没有区别,您希望有什么不同?

        基于本站 (http://javatechniques.com/blog/dateformat-and-simpledateformat-examples/):

        “a”->“上午”

        “aa” -> “上午”

        【讨论】:

          【解决方案5】:

          那么你的选择是

          time = time.substring(0,time.length()-1);
          

          :) 很傻,但会起作用

          【讨论】:

            猜你喜欢
            • 2010-12-31
            • 2012-11-18
            • 1970-01-01
            • 1970-01-01
            • 2013-12-24
            • 1970-01-01
            • 2018-06-27
            • 2019-01-12
            • 2012-07-03
            相关资源
            最近更新 更多