【问题标题】:Date Formatting using only date and month?仅使用日期和月份的日期格式?
【发布时间】:2014-12-03 11:20:15
【问题描述】:

我需要构建一个仅显示日期和月份的日期示例:- 23 Dec。我只有日值和月值,但是如何使用 SimpleDateFormat 构造格式为“dd-MMM”的格式化日期。如何修改以下方法以返回格式化日期?

public String formatDate(String day, String month, String year) {
        // Do something with the date chosen by the user
        SimpleDateFormat df = new SimpleDateFormat("dd-MMM");
    }

假设如果我调用 formatDate("11","1","") 之类的上述方法,那么它应该返回“11 Jan”。

【问题讨论】:

    标签: android simpledateformat android-date


    【解决方案1】:

    这应该可行:

    年份值设置为 0,因为您没有它,但您可以将其传递给 set 方法。

    public String formatDate(String day, String month, String year) {
      // Do something with the date chosen by the user
      SimpleDateFormat df = new SimpleDateFormat("dd-MMM");
    
      Calendar c = Calendar.getInstance();
      c.set(0, Integer.parseInt(month)-1, Integer.parseInt(day));
      return df.format(c.getTimeInMillis());
    

    }

    【讨论】:

      【解决方案2】:

      tl;博士

      MonthDay.of( Month.JANUARY , 23 )
              .toString() 
      

      ……或者……

      MonthDay.of( Month.JANUARY , 23 )
              .format( DateTimeFormatter.ofPattern( "dd MMM" ) ) 
      

      MonthDay

      如果您想表示没有任何年份的月份和日期,请使用 MonthDay 类。专为此目的而构建。

      一个月和一天的标准ISO 8601 格式是“--MM-DD”。类似于“YYYY-MM-DD”的日期格式,但用连字符代替年份。

      java.time 类在解析/生成字符串时默认使用 ISO 8601 格式。因此无需为此类字符串指定格式模式。对于您的自定义格式,我们必须定义一个格式化程序。我建议尽可能坚持使用 ISO 8601 格式。

      MonthDay md = MonthDay.of( 12 , 23 );
      DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM" );
      String output = md.format( f );
      

      md.toString(): --12-23

      输出:12 月 23 日

      live code in IdeOne.com

      您的问题自相矛盾,有时以您想要的格式显示连字符,但在另一种情况下显示空格。如果你想要空间,请使用DateTimeFormatter.ofPattern( "dd MMM" )


      关于java.time

      java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.DateCalendarSimpleDateFormat

      Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。

      要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310

      从哪里获得 java.time 类?

      ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如IntervalYearWeekYearQuartermore

      【讨论】:

        猜你喜欢
        • 2020-10-18
        • 1970-01-01
        • 2011-09-24
        • 2020-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-20
        相关资源
        最近更新 更多