在Java中的Oracle `next_day`函数的等价方法是什么。

huangapple go评论88阅读模式
英文:

Oracle next_day function equivalent in JAVA

问题

/**
 * @param date
 * @param weekDay
 * @return Gives the date for the next weekday specified in the parameter.
 */    
public Date getNextDay(Date value, String weekday) {
    Calendar date1 = Calendar.getInstance();
    date1.setTime(value);

    String[] weekdays = {"SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"};
    int targetDayOfWeek = -1;

    for (int i = 0; i < weekdays.length; i++) {
        if (weekday.equalsIgnoreCase(weekdays[i])) {
            targetDayOfWeek = i;
            break;
        }
    }

    if (targetDayOfWeek == -1) {
        throw new IllegalArgumentException("Invalid weekday provided.");
    }

    int currentDayOfWeek = date1.get(Calendar.DAY_OF_WEEK);
    int daysUntilTarget = (targetDayOfWeek - currentDayOfWeek + 7) % 7;

    date1.add(Calendar.DATE, daysUntilTarget);
    return date1.getTime();
}

This revised code uses an array of weekdays and calculates the number of days needed to reach the next target weekday in a more concise manner. It eliminates the need for multiple if-else conditions and simplifies the logic.

英文:

I wanted to make a method which works similar to as oracle's next_day() function, below is my code which accepts date n weekday in MONDAY,TUESDAY etc. and returns a date which falls on the next given day from the input date.

/**
 * @param date
 * @param weekDay
 * @return Gives the date for next weekday specified in the parameter.
 */    
public Date getNextDay(Date value, String weekday) {
    Calendar date1 = Calendar.getInstance();
    date1.setTime(value);
        
    if (weekday.equalsIgnoreCase(&quot;MONDAY&quot;))	{
		while (date1.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
			date1.add(Calendar.DATE, 1);
        }
	} else if (weekday.equalsIgnoreCase(&quot;TUESDAY&quot;)) {
		while (date1.get(Calendar.DAY_OF_WEEK) != Calendar.TUESDAY) {
			date1.add(Calendar.DATE, 1);
        }
    } else if (weekday.equalsIgnoreCase(&quot;WEDNESDAY&quot;)) {
        while (date1.get(Calendar.DAY_OF_WEEK) != Calendar.WEDNESDAY) {
        	date1.add(Calendar.DATE, 1);
        }
    } else if (weekday.equalsIgnoreCase(&quot;THURSDAY&quot;)) {
        while (date1.get(Calendar.DAY_OF_WEEK) != Calendar.THURSDAY) {
        	date1.add(Calendar.DATE, 1);
        }
    } else if (weekday.equalsIgnoreCase(&quot;FRIDAY&quot;)) {
        while (date1.get(Calendar.DAY_OF_WEEK) != Calendar.FRIDAY) {
			date1.add(Calendar.DATE, 1);
		}
	} else if (weekday.equalsIgnoreCase(&quot;SATURDAY&quot;)) {
		while (date1.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY) {
			date1.add(Calendar.DATE, 1);
		}
	} else {
        while (date1.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
			date1.add(Calendar.DATE, 1);
		}
    }
        	    
    return date1.getTime();
}

Please suggest a better way of doing this.

答案1

得分: 4

我建议您使用现代java.time 日期时间 API 进行操作。从 教程:日期时间 中可以了解更多有关现代日期时间 API 的信息。java.util 日期时间 API 和 SimpleDateFormat 已过时且容易出错。如果您未使用 Java 8,您仍可以通过 ThreeTenABP 库来使用 Java 8 的日期时间 API。

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

public class Main {
    public static void main(String[] args) {
        // Tests
        
        // Next occurrence
        System.out.println(getNextDay(LocalDate.now(), "Monday"));
        System.out.println(getNextDay(LocalDate.now(), "Wednesday"));
        
        // Same (if date falls on the given day) or next occurrence
        System.out.println(getSameOrNextDay(LocalDate.now(), "Monday"));
        System.out.println(getSameOrNextDay(LocalDate.now(), "Wednesday"));
    }
    
    static LocalDate getNextDay(LocalDate value, String weekday) {
        return value.with(TemporalAdjusters.next(DayOfWeek.valueOf(weekday.toUpperCase())));
    }
    
    static LocalDate getSameOrNextDay(LocalDate value, String weekday) {
        return value.with(TemporalAdjusters.nextOrSame(DayOfWeek.valueOf(weekday.toUpperCase())));
    }
}

输出:

2020-09-28
2020-09-30
2020-09-28
2020-09-23
英文:

I recommend you do it using the modern java.time date-time API. Learn more about the modern date-time API from Trail: Date Time. The java.util date-time API and SimpleDateFormat are outdated and error-prone. In case you are not using Java-8, you can still use Java-8 date-time API through ThreeTenABP library.

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
public class Main {
public static void main(String[] args) {
// Tests
// Next occurrence
System.out.println(getNextDay(LocalDate.now(), &quot;Monday&quot;));
System.out.println(getNextDay(LocalDate.now(), &quot;Wednesday&quot;));
// Same (if date falls on the given day) or next occurrence
System.out.println(getSameOrNextDay(LocalDate.now(), &quot;Monday&quot;));
System.out.println(getSameOrNextDay(LocalDate.now(), &quot;Wednesday&quot;));
}
static LocalDate getNextDay(LocalDate value, String weekday) {
return value.with(TemporalAdjusters.next(DayOfWeek.valueOf(weekday.toUpperCase())));
}
static LocalDate getSameOrNextDay(LocalDate value, String weekday) {
return value.with(TemporalAdjusters.nextOrSame(DayOfWeek.valueOf(weekday.toUpperCase())));
}
}

Output:

2020-09-28
2020-09-30
2020-09-28
2020-09-23

答案2

得分: 2

如果您对明天感兴趣,我建议使用java.time.LocalDate而不是java.util.Date

以下代码接受一个LocalDate,以及一个String(必须是大写字母的整个星期几),并返回代表最近未来日期的LocalDate,该日期具有给定的星期几:

public static LocalDate nextDay(LocalDate sourceDay, String weekday) {
	// 将星期几解析为枚举值
	DayOfWeek dayOfWeek = DayOfWeek.valueOf(weekday);
	// 检查日期是否与给定的LocalDate的星期几相同
	if (sourceDay.getDayOfWeek().equals(dayOfWeek)) {
		// 并返回一周后的LocalDate
		return sourceDay.plusWeeks(1);
	} else {
		// 否则将一天添加到给定日期
		LocalDate nextDayOfWeek = sourceDay.plusDays(1);
		// 并重复此步骤,直到达到给定日期的星期几
		while (nextDayOfWeek.getDayOfWeek() != dayOfWeek) {
			nextDayOfWeek = nextDayOfWeek.plusDays(1);
		}
		// 然后返回未来日期
		return nextDayOfWeek;
	}
}

您可以在main方法中这样使用它:

public static void main(String[] args) {
	System.out.println(nextDay(LocalDate.now(), "FRIDAY")
						.format(DateTimeFormatter.ofPattern("uuuu-MM-dd '('EEEE')'",
								Locale.ENGLISH)));
}

输出(今天2020-09-23):

2020-09-25 (Friday)
英文:

If you are interested in the next day I'll suggest using a java.time.LocalDate instead of a java.util.Date.

The following code accepts such a LocalDate along with a String (that needs to be a full day of week in upper case letters) and returns the LocalDate representing the nearest future date which has the given day of week:

public static LocalDate nextDay(LocalDate sourceDay, String weekday) {
	// parse the day of week to an enum value
	DayOfWeek dayOfWeek = DayOfWeek.valueOf(weekday);
	// check if the day is the same as the one of the given LocalDate
	if (sourceDay.getDayOfWeek().equals(dayOfWeek)) {
		// and return the LocalDate that&#39;s a week later
		return sourceDay.plusWeeks(1);
	} else {
		// otherwise add a day to the given date
		LocalDate nextDayOfWeek = sourceDay.plusDays(1);
		// and do that until the day of week of the given date is reached
		while (nextDayOfWeek.getDayOfWeek() != dayOfWeek) {
			nextDayOfWeek = nextDayOfWeek.plusDays(1);
		}
		// then return the future date
		return nextDayOfWeek;
	}
}

You can use it in a main like this:

	public static void main(String[] args) {
		System.out.println(nextDay(LocalDate.now(), &quot;FRIDAY&quot;)
							.format(DateTimeFormatter.ofPattern(&quot;uuuu-MM-dd &#39;(&#39;EEEE&#39;)&#39;&quot;,
									Locale.ENGLISH)));
	}

Output (today &rArr; 2020-09-23):

2020-09-25 (Friday)

答案3

得分: 1

使用“新的” java.time.DayOfWeekjava.time.LocalDate 类:

public LocalDate getNextDay(
    final LocalDate value,
    final DayOfWeek day
)
{
    int currentDay = value.getDayOfWeek().getValue();
    int expectedDay = day.getValue();
    if (currentDay >= expectedDay)
    {
        expectedDay += 7;
    }
    return value.plusDays(expectedDay - currentDay);
}
英文:

Use the "new" java.time.DayOfWeek and java.time.LocalDate classes:

public LocalDate getNextDay(
    final LocalDate value,
    final DayOfWeek day
)
{
    int currentDay = value.getDayOfWeek().getValue();
    int expectedDay = day.getValue();
    if ( currentDay &gt;= expectedDay )
    {
        expectedDay += 7;
    }
    return value.plusDays( expectedDay - currentDay );
}

huangapple
  • 本文由 发表于 2020年9月23日 20:18:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/64027813.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定