【问题标题】:java - show date method in Calendar class [duplicate]java - 在日历类中显示日期方法
【发布时间】:2018-03-01 07:54:55
【问题描述】:

这里是 Java 菜鸟。除了 .getTime() 方法之外,还有其他方法可以在 Calendar 类中显示日期吗?我想要尽可能接近 dd/mm/yyyy 的东西。我可以创建一个方法来拆分 getTime 方法返回的字符串并在那里选择某些项目以形成我想要的日期格式,蛮力进入它。我想知道是否有更简单的方法或内置方法。

我正在解决一个涉及日期的问题。我只是注意到做一个while循环,使用.add(Calendar.DAY_OF_MONTH, 1)进行“每天”递增可能是每天检查给定条件的一种方法。下一个问题是返回符合条件的日期。这就是让我找到java.util.Calendar 的原因。

【问题讨论】:

  • getTime() 返回一个java.util.Date - 听起来你正在尝试格式化 Calendar...你可以使用SimpleDateFormat,但你'如果可能的话,最好转移到java.time API。
  • 拜托 - 与 java.time.* 相比,java.util.Date 和 java.util.Calendar API 基本上是可怕。但我也会尽可能地在域中工作 - 你说你想“返回符合条件的日期” - 我会将其返回为 LocalDate 而不是 String
  • @mike,当您想为您的问题添加更多信息(这通常是值得赞赏的)时,最好编辑问题而不是发表评论。这一次我为你做到了。
  • 您使用了错误的类。它们设计得非常糟糕、令人困惑、麻烦,现在被 java.time 类所取代。您的问题已经在 Stack Overflow 上被多次询问和回答。在发布之前,请务必彻底搜索。搜索:LocalDate、ZonedDateTime 和 DateTimeFormatter。此外,在发帖时,要像激光一样专注于一个特定的编程问题;您的问题在这里涉及到多个方向。

标签: java string date calendar date-formatting


【解决方案1】:

使用 SimpleDateFormat 类可以完成最简单的日期格式化方法:

Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
System.out.println( sdf.format(calendar.getTime()) );

您可以在此处找到修改格式的模式:https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

【讨论】:

    【解决方案2】:

    这会有所帮助 - Javadoc

    创建一个静态方法并使用 SimpleDateFormat 以您想要的任何格式解析日期

    【讨论】:

      【解决方案3】:

      java.time

      我建议您使用the modern Java date and time API known as java.time or JSR-310。例如:

          final LocalDate beginDate = LocalDate.of(2017, Month.JANUARY, 1);
          final LocalDate endDate = LocalDate.of(2020, Month.DECEMBER, 31);
          final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
      
          LocalDate currentDate = beginDate;
          while (currentDate.isBefore(endDate) && ! fulfilsCondition(currentDate)) {
              currentDate = currentDate.plusDays(1);
          }
          if (fulfilsCondition(currentDate)) {
              System.out.println("This date hit the condition: " + currentDate.format(dateFormatter));
          } else {
              System.out.println("No date in the range hit the condition");
          }
      

      我相信你会在代码中的两个地方填写你的条件的测试。根据您的操作方式,代码将打印例如:

      This date hit the condition: 25/09/2018
      

      如果您尚未使用 Java 8 或更高版本,则需要使用 ThreeTen Backport 才能使用现代 API。

      避免使用过时的Calendar

      CalendarSimpleDateFormat 和朋友的类早已过时,而我使用的现代 API 更好、更自然、更易于使用。旧的类从 Java 1 开始就已经存在,所以有很多网站告诉你应该使用它们。这不再是真的。

      【讨论】:

        猜你喜欢
        • 2012-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-13
        • 2022-01-14
        • 1970-01-01
        • 2011-05-18
        • 1970-01-01
        相关资源
        最近更新 更多