java - 在日历中显示日期的方法 class

java - show date method in Calendar class

Java 菜鸟在这里。除了 .getTime() 方法之外,有没有办法在 Calendar class 中显示日期?我想要尽可能接近 dd/mm/yyyy 的东西。我可以制作一种方法,通过 getTime 方法拆分字符串 returned 并选择其中的某些项目以形成我想要的日期格式,强行进入它。我想知道是否有更简单的方法或内置方法。

我正在解决一个涉及日期的问题。我只是注意到做一个 while 循环,使用 .add(Calendar.DAY_OF_MONTH, 1) 递增 "per day" 可能是一种每天检查给定条件的方法。下一个问题是 return 满足条件的日期。无论如何,这就是让我 java.util.Calendar 的原因。

使用 SimpleDateFormat 可以完成设置日期格式的最简单方法 class:

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

这会有所帮助 - Javadoc

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

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 class

classes Calendar, SimpleDateFormat 和朋友们早就过时了,我使用的现代 API 更好,更自然,更直接一起工作。旧的 classes 从大约 Java 1 开始就已经存在,所以有很多网站告诉您应该使用它们。这不再是真的。