java-在Calendar类中显示日期方法

java-在Calendar类中显示日期方法,java,string,date,calendar,date-formatting,Java,String,Date,Calendar,Date Formatting,这里是爪哇岛。除了.getTime()方法之外,还有没有其他方法可以在Calendar类中显示日期?我想要尽可能接近dd/mm/yyyy的东西。我可以创建一个方法,将getTime方法返回的字符串拆分,并选择其中的某些项来形成我想要的日期格式,然后强制执行。我想知道是否有一个更简单的方法或内置的方法来实现这一点 我正在解决一个涉及日期的问题。我刚刚注意到,使用.add(Calendar.day\u OF\u MONTH,1)执行while循环,以“每天”增量检查每天的给定条件。下一个问题是返回符

这里是爪哇岛。除了.getTime()方法之外,还有没有其他方法可以在Calendar类中显示日期?我想要尽可能接近dd/mm/yyyy的东西。我可以创建一个方法,将getTime方法返回的字符串拆分,并选择其中的某些项来形成我想要的日期格式,然后强制执行。我想知道是否有一个更简单的方法或内置的方法来实现这一点


我正在解决一个涉及日期的问题。我刚刚注意到,使用
.add(Calendar.day\u OF\u MONTH,1)
执行while循环,以“每天”增量检查每天的给定条件。下一个问题是返回符合条件的日期。这就是我为什么选择了
java.util.Calendar

格式化日期的最简单方法是使用SimpleDataFormat类:

Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
System.out.println( sdf.format(calendar.getTime()) );
您可以在此处找到修改格式的模式:

这将有助于-

创建一个静态方法,并使用SimpleDataFormat以您想要的任何格式解析日期 我建议你使用。例如:

    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
我相信你会在代码的两个地方填写你的条件测试。根据您的操作方式,代码将打印,例如:

    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
如果您尚未使用Java8或更高版本,则需要使用以使用现代API

避免使用过时的
日历

Calendar
SimpleDateFormat
和friends早已过时,而我使用的现代API更为友好、自然、直观。旧类从Java1开始就存在了,因此有很多网站告诉您应该使用它们。这不再是真的。

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