Check A Date String If Weekend In Java


Today I need a Java function to check if a given time string e.g. 20130218001203638, (e.g, 18 of Feb, 2013) is weekend, i.e Saturday or Sunday. So, the following is a quick solution based on the Calendar class. However, the following assumes the input string is in valid format, i.e. there is no exception handling if the date string goes wrong, e.g. less than 8 characters or contains invalid characters.

1
2
3
4
5
6
7
8
9
public static boolean isWeekend(String ts)
{
    int year = Integer.parseInt(ts.substring(0, 4));
    int month = Integer.parseInt(ts.substring(4, 6));
    int day = Integer.parseInt(ts.substring(6, 8));
    Calendar cal = new GregorianCalendar(year, month - 1, day);
    int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
    return (Calendar.SUNDAY == dayOfWeek || Calendar.SATURDAY == dayOfWeek);
}
public static boolean isWeekend(String ts)
{
	int year = Integer.parseInt(ts.substring(0, 4));
	int month = Integer.parseInt(ts.substring(4, 6));
	int day = Integer.parseInt(ts.substring(6, 8));
	Calendar cal = new GregorianCalendar(year, month - 1, day);
	int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
	return (Calendar.SUNDAY == dayOfWeek || Calendar.SATURDAY == dayOfWeek);
}

Why do I need this function? because in RTB (Real Time Bidding) evaluation algorithm, there is a fact that on weekends, the Click and Conversion rate is higher than weekdays i.e weekend effect. It is also necessary to note that the month in Java starts with zero not one.

Another note I want to make here is in Java you can use the command line switch -Xmx to increase the java heap memory, in case you come across the out-of-memory error (GC limit), java -Xmx256m, which to give the heap 256 mb of memory.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
272 words
Last Post: Using Voice Engine in VBScript
Next Post: Absolute keyword in Delphi

The Permanent URL is: Check A Date String If Weekend In Java

Leave a Reply