All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.gitlab.schedule4j.cron.subpart.XthDayOfMonthSubpart Maven / Gradle / Ivy

/*
 * Created on 2010-03-08
 * 
 * Copyright 2010 Dirk Buchhorn
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.gitlab.schedule4j.cron.subpart;

import java.time.DayOfWeek;
import java.time.ZonedDateTime;
import java.time.temporal.TemporalAdjusters;

/**
 * This class represents the 'X#X' in a day-of-week cron part.
 * 
 * @author Dirk Buchhorn
 */
public class XthDayOfMonthSubpart extends AbstractDayOfMonthSubpart
{
	private int dayOfWeek;
	private int count;

	public XthDayOfMonthSubpart(int dayOfWeek, int count)
	{
		super();
		this.dayOfWeek = dayOfWeek;
		this.count = count;
	}

	@Override
	protected int calculateDayOfMonth(ZonedDateTime dateTime, int monthOffset)
	{
		ZonedDateTime dt = dateTime.with(TemporalAdjusters.firstDayOfMonth()).plusMonths(monthOffset);
		int maxValue = dt.with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth();
		DayOfWeek firstDayOfWeek = dt.getDayOfWeek();
		// correct the start value - if the first day of the month is a Friday then we have -4 as start value
		int start = 1 - firstDayOfWeek.getValue();
		if (Math.abs(start) >= dayOfWeek)
		{
			start += 7;
		}
		int day = start + dayOfWeek + (7 * (count - 1));
		if (day > maxValue)
		{
			day = -1;
		}
		return day;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy