-4

Can anyone help me to complete this function in Java? thanks

// e.g. "20130218001203638"
boolean isWeekend(String date)
{
    ... ...
}

Find a post giving the exact answer I want.

Check A Date String If Weekend In Java

justyy
  • 5,831
  • 4
  • 40
  • 73
  • 1
    Lookup calendar & date classes. I think Calendar since date got deprecated – Caffeinated May 14 '13 at 15:41
  • See Calendar class 4 clues – Caffeinated May 14 '13 at 15:42
  • 2
    That string can be parsed into a `Calendar` using a `DateFormatter` (IIRC). A `Calendar` can tell you the day of the week. – Lee Meador May 14 '13 at 15:42
  • 2
    Possible duplicate of [java example to get all weekend dates in a given month](http://stackoverflow.com/questions/3272454/java-example-to-get-all-weekend-dates-in-a-given-month) – Smit May 14 '13 at 15:45
  • possible duplicate of [How to get localized short day-in-week name (Mo/Tu/We/Th...)](http://stackoverflow.com/questions/3790954/how-to-get-localized-short-day-in-week-name-mo-tu-we-th) – Burkhard May 14 '13 at 15:48

3 Answers3

5

Calendar#get(DAY_OF_WEEK) it return values SUNDAY, MONDAY, ...

what you can just conditionally check with Calendar.SATURDAY or Calendar.SUNDAY.

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
1

Something like this should help:

boolean isWeekend = false;
Date date = new Date();
//assuming your date string is time in long format, 
//if not then use SimpleDateFormat class
date.setTime(Long.parseLong("20130218001203638"));
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);

if(calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY ||
         calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
    isWeekend = true;
}
return isWeekend;
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
0

Just as date calculation is wearisome

SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
Date d = df.parse(date);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
int wday = cal.get(Calendar.DAY_OF_WEEK);
return wday == Calendar.SATURDAY || wday == Calendar.SUNDAY;
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138