如何在Java中找到一个月的最后一个工作日

时间:2017-03-03 09:55:11

标签: java android

如何在Java中找到一个月的最后一个工作日。如果一个月的最后一天是星期六或星期日,则最后一个工作日应该是星期五。例如,如果3月31日是星期日,则最后一个工作日是星期五3月29日。

获取当月

Date today = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(today);
calendar.add(Calendar.MONTH, 1);

2 个答案:

答案 0 :(得分:4)

TL;博士

LocalDate.now( ZoneId.of( "America/Montreal" ) )                     // Today
         .with( TemporalAdjusters.firstDayOfNextMonth() )            // First of next month.
         .with( org.threeten.extra.Temporals.previousWorkingDay() )  // Move backwards in time, looking for first day that is not Saturday nor Sunday.

避免遗留类

你正在使用麻烦的旧日期时间类,现在是旧的,取而代之的是java.time类。

Table of date-time types in Java, both modern and legacy.

使用java.time

LocalDate类表示没有时间且没有时区的仅限日期的值。

时区对于确定日期至关重要。对于任何给定的时刻,日期在全球范围内因地区而异。例如,在Paris France午夜后的几分钟是新的一天,而Montréal Québec中仍然是“昨天”。

continent/region的格式指定proper time zone name,例如America/MontrealAfrica/CasablancaPacific/Auckland。切勿使用诸如ESTIST之类的3-4字母缩写,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

TemporalAdjuster界面提供了一种调整日期时间值的方法。 TemporalAdjusters类(注意复数s)提供了几个方便的实现。

LocalDate endOfMonth = today.with( TemporalAdjusters.lastDayOfMonth() );

ThreeTen-Extra项目扩展了具有附加功能的java.time。这包括更多TemporalAdjuster实现。其中一个是previousWorkingDay跳过周六和周日。要使用此功能,我们需要超过月底,因为那一天本身可能是工作日。

LocalDate previousWorkingDay = endOfMonth.plusDays( 1 ).with( org.threeten.extra.Temporals.previousWorkingDay() );

关于java.time

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

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

要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310

从哪里获取java.time类?

ThreeTen-Extra项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如IntervalYearWeekYearQuartermore

答案 1 :(得分:-1)

试试这个

Date today = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(today);

calendar.add(Calendar.MONTH, 1);//Used for finding next month
calendar.set(Calendar.DAY_OF_MONTH, 1);//Setting the Day of month as 1 for starting    
do{
       calendar.add(Calendar.DATE, -1); //In the first case decease day by 1 so get the this months last day
   } while (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY
           || calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY ); // Checking whether the last day is saturday or sunday then it will decrease by 1
    Date lastDayOfMonth = calendar.getTime();
    DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    System.out.println("Today: " + sdf.format(today));
    System.out.println("Last Day of Month: " +df.format(lastDayOfMonth));