Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first day of a given week number in Java

Tags:

Let me explain myself. By knowing the week number and the year of a date:

Date curr = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(curr); int nweek = cal.WEEK_OF_YEAR; int year = cal.YEAR; 

But now I don't know how to get the date of the first day of that week. I've been looking in Calendar, Date, DateFormat but nothing that may be useful...

Any suggestion? (working in Java)

like image 748
framara Avatar asked Jan 21 '10 12:01

framara


People also ask

What is the first day of the week in Java?

By default, java. time uses the ISO 8601 standard. So Monday is the first day of the week (1) and Sunday is last (7). And same for the month.

How do you start the day of the week?

Starts Monday or Sunday According to international standard ISO 8601, Monday is the first day of the week. It is followed by Tuesday, Wednesday, Thursday, Friday, and Saturday. Sunday is the 7th and last day of the week.

How do you get the day of the week from a date in Java?

To get the day of week for a particular date in Java, use the Calendar. DAY_OF_WEEK constant.


2 Answers

Those fields does not return the values. Those are constants which identifies the fields in the Calendar object which you can get/set/add. To achieve what you want, you first need to get a Calendar, clear it and set the known values. It will automatically set the date to first day of that week.

// We know week number and year. int week = 3; int year = 2010;  // Get calendar, clear it and set week number and year. Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.WEEK_OF_YEAR, week); calendar.set(Calendar.YEAR, year);  // Now get the first day of week. Date date = calendar.getTime(); 

Please learn to read the javadocs to learn how to use classes/methods/fields and do not try to poke random in your IDE ;)

That said, the java.util.Date and java.util.Calendar are epic failures. If you can, consider switching to Joda Time.

like image 186
BalusC Avatar answered Sep 23 '22 14:09

BalusC


Try this:

public static Calendar setWeekStart(Calendar calendar) {   while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {     calendar.add(Calendar.DATE, -1);   }   setDayStart(calendar); // method which sets H:M:S:ms to 0   return calendar; } 
like image 27
Vojta Avatar answered Sep 23 '22 14:09

Vojta