This question already has answers here:
Get last week date range for a date in Java
(5 answers)
Closed 5 years ago.
My requirement is to get the start and end date of the week when date is passed. I have searched and i found tons of answers but confused with which one is best to use.In one of the thread i found the below code:
Calendar c = Calendar.getInstance();
c.setTime(new Date("8/16/2017"));
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
System.out.println("day :" + dayOfWeek);
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
System.out.println("start of week day :" + c.getTime());
output:
day :4
start of week day :Sun Aug 13 00:00:00 EDT 2017
I see a bug in the above code output. Start of the week should be Monday Aug14 but it shows Sun Aug13. Any suggestions to get the start date and end date of the week when date is passed as a String dynamically.
--EDITED--
I'm looking for java code which returns the first and last day date's of the week when date is passed.
import java.time.LocalDate;
import static java.time.DayOfWeek.MONDAY;
import static java.time.DayOfWeek.SUNDAY;
import static java.time.temporal.TemporalAdjusters.nextOrSame;
import static java.time.temporal.TemporalAdjusters.previousOrSame;
public class FirstAndLast
{
public static void main(String[] args)
{
LocalDate today = LocalDate.now();
LocalDate monday = today.with(previousOrSame(MONDAY));
LocalDate sunday = today.with(nextOrSame(SUNDAY));
System.out.println("Today: " + today);
System.out.println("Monday of the Week: " + monday);
System.out.println("Sunday of the Week: " + sunday);
}
}
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY); //Line2
c.setTime(new Date("8/16/2017"));
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
System.out.println("day :" + dayOfWeek);
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
System.out.println("start of week day :" + c.getTime());
Set the first day of the week to Monday as in line 2.
Now the output will be
day :4
start of week day :Mon Aug 14 00:00:00 EDT 2017
Related
This question already has answers here:
Y returns 2012 while y returns 2011 in SimpleDateFormat
(5 answers)
Why does sdf.format(date) converts 2018-12-30 to 2019-12-30 in java? [duplicate]
(3 answers)
Closed 3 years ago.
From document SimpleDateTimePattern, yy should be the same with YY.
Today is Dec 30, 2019, now we get YY for today is 20, yy for today is 19. What's the difference between yy and YY in Java Time Pattern?
yy is the calendar year, while YY is a week year. A week year can be different from the calendar year depending on which day the first of January falls. For example see ISO-8601 week year.
Today (30 December 2019) is a good example, the calendar year is 2019, but the week year is 2020, because this week is week 1 of 2020. So yy will result in 19, while YY results in 20.
The definition of the first week of a year from the wikipedia page:
The ISO 8601 definition for week 01 is the week with the Gregorian
year's first Thursday in it. The following definitions based on
properties of this week are mutually equivalent, since the ISO week
starts with Monday:
It is the first week with a majority (4 or more) of its days in January.
Its first day is the Monday nearest to 1 January.
It has 4 January in it. Hence the earliest possible first week extends from Monday 29 December (previous Gregorian year) to Sunday 4
January, the latest possible first week extends from Monday 4 January
to Sunday 10 January.
It has the year's first working day in it, if Saturdays, Sundays and 1 January are not working days.
If 1 January is on a Monday, Tuesday, Wednesday or Thursday, it is in
week 01. If 1 January is on a Friday, it is part of week 53 of the
previous year. If it is on a Saturday, it is part of the last week of
the previous year which is numbered 52 in a common year and 53 in a
leap year. If it is on a Sunday, it is part of week 52 of the previous
year.
Some locales, like for example the US, don't follow ISO-8601, because there they use Sunday as the first day of the week, but they have similar rules for week years.
You have it in you link:
y Year Year 1996; 96
Y Week year Year 2009; 09
Week year can be different, for example this new year week, than current year
Week year defines as year's first Thursday:
The first week of the year is the week that contains that year's first Thursday
They both represent a year but yyyy represents the calendar year while
YYYY represents the year of the week.
An example illustrates this much better than words ever could.
package datetest;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
public static void main(String[] args) {
try {
String[] dates = {"2018-12-01", "2018-12-31", "2019-01-01"};
for (String date: dates) {
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd");
Date d = dt.parse(date);
SimpleDateFormat dtYYYY = new SimpleDateFormat("YYYY");
SimpleDateFormat dtyyyy = new SimpleDateFormat("yyyy");
System.out.println("For date :" + date + " the YYYY year is : " + dtYYYY.format(d) + " while for yyyy it's " + dtyyyy.format(d));
}
} catch (Exception e) {
System.out.println("Failed with exception: " + e);
}
}
}
Output
For date : 2018-12-01 the YYYY year is : 2018 while for yyyy it's 2018
For date : 2018-12-31 the YYYY year is : 2019 while for yyyy it's 2018
For date : 2019-01-01 the YYYY year is : 2019 while for yyyy it's 2019
I want to select Sunday before first Monday of the passed month.
That Sunday may be in the same month or the previous month but I want date of Sunday. I tried below logic for getting Sunday, it works for the current month but if I try passing some another month like Nov-2017 then again I have to change MONDAY-2 to MONDAY-3. So this is not the correct way. So how can I achieve this ?
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Date " + c.getTime());
c.set(Calendar.DAY_OF_MONTH, Calendar.MONDAY - 2);
System.out.println("Date " + c.getTime());
I want to pass date to the code. So how can i do it ? like if I have date saved in variable then according to the input provided by that variable it should calculate the logic and provide the output
#Test
public void testDate() throws ParseException {
SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
Date d = fmt.parse("01-Nov-2017");
System.out.println(d);
Calendar c = Calendar.getInstance();
c.setTime(d);
getSundayBefore1thMondayOfMonth(c);
}
public void getSundayBefore1thMondayOfMonth(Calendar c) {
c.set(Calendar.DAY_OF_MONTH, 1);
int wd = c.get(Calendar.DAY_OF_WEEK);
if (wd > Calendar.MONDAY ) {
c.add(Calendar.DAY_OF_MONTH, 7);
}
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println(c.getTime());
c.add(Calendar.DAY_OF_MONTH, -1);
System.out.println(c.getTime());
}
Wed Nov 01 00:00:00 CST 2017
Mon Nov 06 00:00:00 CST 2017
Sun Nov 05 00:00:00 CST 2017
If you are using Java 8, Then you can use java.time library and you can just use :
LocalDate firstMondayOfMonth = LocalDate.now().with(
TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)
);// This return 2018-01-01
LocalDate sunday = firstMondayOfMonth.minusDays(1);//This return 2017-12-31
To test with November 2017 you can use LocalDate.of instead LocalDate.now() like this :
LocalDate firstMondayOfMonth = LocalDate.of(2017, Month.NOVEMBER, 1).with(
TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)
);// This return 2017-11-06
LocalDate firstSunday = firstMondayOfMonth.minusDays(1);// This return 2017-11-05
tl;dr
YearMonth
.now() // Current year-month. Tip: Better to pass the optional time zone, as shown further down in this Answer.
.atDay( 1 ) // First of the current month.
.with( TemporalAdjusters.nextOrSame( DayOfWeek.MONDAY ) ) // Move from first day of month to the following Monday, or stay on the first if it already a Monday.
.minusDays( 1 ) // Move back one day from Monday to get a Sunday. May be in current month or in previous month.
java.time
You are using troublesome old date-date classes that are now legacy, supplanted by the java.time classes.
Determining the current month means determining the current date. Determining the current date requires a time zone. For any given moment, the date varies around the globe by zone.
ZoneId z = ZoneId.of( “Africa/Tunis” ) ;
The YearMonth class represent the entire month.
YearMonth currentYearMonth = YearMonth.now( z ) ;
From that we can get the first of the month.
LocalDate firstOfMonth = currentYearMonth.atDay( 1 ) ;
We can move to a certain day of the week by calling on a TemporalAdjuster.
LocalDate firstMondayOfMonth = firstOfMonth.with( TemporalAdjusters.nextOrSame( DayOfWeek.MONDAY ) ) ;
LocalDate sundayBeforeFirstMondayOfMonth = firstMondayOfMonth.with( TemporalAdjusters.previous( DayOfWeek.SUNDAY ) ) ;
Logically, that last line could be replaced with .minusDays( 1 ) as we know the previous Sunday immediately precedes our Monday by definition.
In the code below, first we get the first monday in the month. Then we just subtract 1 day.
// input
int year = 2017;
int month = Calendar.NOVEMBER;
// get first monday of the month
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
c.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
c.set(Calendar.MONTH, month);
c.set(Calendar.YEAR, year);
System.out.println("Date " + c.getTime());
// subtract 1
c.add(Calendar.DAY_OF_MONTH, -1);
System.out.println("Date " + c.getTime());
Try this:
Calendar calendar=Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
calendar.add(Calendar.DATE, -1);
System.out.println(calendar.getTime());
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek( Calendar.MONDAY); //Monday is first day of a week
c.setMinimalDaysInFirstWeek( 1); //first week of month is the week that has at least one day in this month
//c.setMinimalDaysInFirstWeek( 7); //first week of month must be a full week
c.set(Calendar.WEEK_OF_MONTH, 1); //move to first week of month
System.out.println("Date " + c.getTime());
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); //move to Monday
System.out.println("Date " + c.getTime());
c.add( Calendar.DAY_OF_MONTH, -1); //go back one day
System.out.println("Date " + c.getTime());
Choose one of the c.setMinimalDaysInFirstWeek() method depending on what the first week of month means to you.
In Java 8, you can use the below code:
public static void getSundayBeforeFirstMondayOfMonth(LocalDate date){
date.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)).minusDays(1);
}
And, call the above method like below as per the requirement:
public static void callerMethod(){
// Call with Current Date
getSundayBeforeFirstMondayOfMonth(LocalDate.now());
//Call with Custom Date
LocalDate customDate = LocalDate.parse("27-11-2017", DateTimeFormatter.ofPattern("DD-MM-YYYY"));
getSundayBeforeFirstMondayOfMonth(customDate);
}
How to get week of particular selected date?
For Example:
My week will start from Monday and ends on Sunday.
So lets say i have selected 25 July 2017. So i want what was the date on monday of that week and what is the date on upcoming Sunday of that week.
The answer should be :: Monday -- 24 July 2017 AND Sunday-- 30 July 2017.
I am not able to find a simple way to get it.
You can see this. It is for the present date.
Calendar cal = Calendar.getInstance();
int week = cal.get(Calendar.WEEK_OF_MONTH);
int day = cal.get(Calendar.DAY_OF_WEEK);
System.out.println(day);
Date mondayDate = null;
if (day > 2) {
int monday = day - 2;
cal.add(Calendar.DATE, -monday);
mondayDate = cal.getTime();
} else {
// cal.add(Calendar.DATE,);
mondayDate = cal.getTime();
}
int sunday = 7 - day + 1;
cal.add(Calendar.DATE, +sunday);
Date sundaydate = cal.getTime();
System.out.println(mondayDate);
System.out.println(sundaydate);
}
In this, we are finding the day of the week.Today we will get
day=2.
Now for monday,we will first check days.
if day=1, means it is sunday.
if day=2, means it is monday.
so for day>2, we are getting date of (day-2) days back. For today, day=1. hence mondaydate= 23 July,2017.
Similarily for sunday, we are getting date of (7-day+1) days later. For today, sunday=5, so after +6, sundaydate= 31 july,2017
Hope this helps :)
You can get like this :
String date = (String) android.text.format.DateFormat.format("dd", date);
String dayOfTheWeek = (String) DateFormat.format("EEEE", date);
For next Sunday you can calculate as per dayOfTheWeek.
I wanto to get the date of a specific day in a specific week, identified by the week number.
Here's an example:
Today it is Monday (03.10.2016) and it is the week with the number 58.
Now i want to get the date of e.g. Friday of this week.
I use Joda-Time within my android application.
Currently Iam creating a LocalDate.
// This is the date of today
private LocalDate reportDate = new LocalDate();
// The number of the week is calculated here
int week = Weeks.weeksBetween(startDate.dayOfWeek().withMinimumValue().minusDays(1),
reportDate.dayOfWeek().withMaximumValue().plusDays(1)).getWeeks();
switch(day_of_week) {
case "Monday":
// Get date of this day in current week
break;
case "Tuesday":
// Get date of this day in current week
break;
// ...
You can use following code to achieve the days as desired,
LocalDateTime yourDate = LocalDateTime.now();
System.out.println(yourDate.getWeekOfWeekyear());
int weekOfyear = yourDate.getWeekOfWeekyear();
//Fetch Week Start Date for Given Week Number
DateTime weekStartDate = new DateTime().withWeekOfWeekyear(weekOfyear);
System.out.println(weekStartDate.toString());
//Fetch Specific Days for given week
DateTime wedDateTime = weekStartDate.withDayOfWeek(DateTimeConstants.WEDNESDAY);
I hope this answer your query.
As per my understanding of your requirement I have implemented below code, just check if it helps you,
First Import Calendar Package As Below
import java.util.Calendar;
Now Create below function
public String getSpecificDate(int weekOfYear, int dayOfWeek)
{
Calendar cal = Calendar.getInstance();
cal.set(Calendar.WEEK_OF_YEAR, weekOfYear);
cal.set(Calendar.DAY_OF_WEEK, dayOfWeek);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH); // 0 to 11
int day = cal.get(Calendar.DAY_OF_MONTH);
String selectedDate = " " + day + "-" + (month+1) + "-" + year;
return selectedDate;
}
// I have passed getSpecificDate(41, 6) and get 7-10-2016 as output
I like to know which week of the month a particular day falls. For example 20-Sep-2012 falls on 4th week of September but the below code displays it as 3 which is not correct. The system is dividing the days by 7 and returning the output and which is not I require. I have searched in Joda API's but not able to find the solution. Please let me know is there any way to figure out the week of a month, a day falls
Calendar ca1 = Calendar.getInstance();
ca1.set(2012,9,20);
int wk=ca1.get(Calendar.WEEK_OF_MONTH);
System.out.println("Week of Month :"+wk);
This is due to two reasons:
The first one is this (from the API):
The first week of a month or year is defined as the earliest seven day period beginning on getFirstDayOfWeek() and containing at least
getMinimalDaysInFirstWeek() days
The default value for this varies (mine was 4), but you can set this to your preferred value with
Calendar.setMinimalDaysInFirstWeek()
The second reason is the one #Timmy brought up in his answer. You need to perform both changes for your code to work. Complete working example:
public static void main(String[] args) {
Calendar ca1 = Calendar.getInstance();
ca1.set(2012, Calendar.SEPTEMBER, 20);
ca1.setMinimalDaysInFirstWeek(1);
int wk = ca1.get(Calendar.WEEK_OF_MONTH);
System.out.println("Week of Month :" + wk);
}
This prints
Week of Month :4
Month is zero-based. So ca1.set(2012,9,20) is actually setting the calendar to October.
To get sure the right month is set try using the month-constants provided by the Calendar-Class.
For those working with Joda time, this is what I am using:
/**
* For a week starting from Sunday, get the week of the month assuming a
* valid week is any week containing at least one day.
*
* 0=Last,1=First,2=Second...5=Fifth
*/
private int getWeekOfMonth( MutableDateTime calendar )
{
long time = calendar.getMillis();
int dayOfMonth = calendar.getDayOfMonth();
int firstWeekday;
int lastDateOfMonth;
int week;
int weeksInMonth;
calendar.setDayOfMonth( 1 );
firstWeekday = calendar.getDayOfWeek();
if (firstWeekday == 7)
{
firstWeekday = 0;
}
calendar.setHourOfDay( 0 );
calendar.addMonths( 1 );
calendar.addDays( -1 );
lastDateOfMonth = calendar.getDayOfMonth();
weeksInMonth = (int)Math.ceil( 1.0*(lastDateOfMonth + firstWeekday)/7 );
week = (byte)(1 + (dayOfMonth + firstWeekday - 1)/7);
week = (week == weeksInMonth)?0:week;
calendar.setMillis( time );
return week;
}
I'm very late to this question, but I feel the full answer is missing, which is, that how weeks are interpreted can differ quite a lot depending on the Locale.
The question seems to need the settings for the US (or a similar Locale), which uses 1 as minimal days in first week, and Sunday as the first day of the week.
The question, and all the answers take a default Calendar instance which comes with 4 as minimal days in first week, and Monday as first day of the week.
A simple demo program shows this :
public static void main(String[] args) {
{
System.out.println("--- ISO ---");
Calendar calendar = Calendar.getInstance();
System.out.println("First day of week : " + calendar.getFirstDayOfWeek());
System.out.println("Minimal days in 1st week : " + calendar.getMinimalDaysInFirstWeek());
calendar.set(2012, Calendar.SEPTEMBER, 20);
int wk = calendar.get(Calendar.WEEK_OF_MONTH);
System.out.println("Week of Month : " + wk);
}
{
System.out.println("--- USA ---");
Calendar calendar = Calendar.getInstance(Locale.US);
System.out.println("First day of week : " + calendar.getFirstDayOfWeek());
System.out.println("Minimal days in 1st week : " + calendar.getMinimalDaysInFirstWeek());
calendar.set(2012, Calendar.SEPTEMBER, 20);
int wk = calendar.get(Calendar.WEEK_OF_MONTH);
System.out.println("Week of Month : " + wk);
}
}
And that yields this output :
--- ISO ---
First day of week : 2
Minimal days in 1st week : 4
Week of Month : 3
--- USA ---
First day of week : 1
Minimal days in 1st week : 1
Week of Month : 4
CONCLUSION :
There's no need to manually set the minimal days in first week, or the first day of week. Just make sure you're using the right Locale.
Extra
Joda time only had support for ISO weeks.
Since Java 8 and the new time API you can go about it like this :
LocalDate localDate = LocalDate.of(2012, 9, 20);
TemporalField usWeekOfMonth = WeekFields.of(Locale.US).weekOfMonth();
TemporalField isoWeekOfMonth = WeekFields.ISO.weekOfMonth();
System.out.println("USA week of month " + usWeekOfMonth.getFrom(localDate));
System.out.println("ISO week of month " + usWeekOfMonth.getFrom(localDate));
Output :
USA week of month 4
ISO week of month 4
And there's even support in the formatter :
DateTimeFormatter usDateTimeFormatter = DateTimeFormatter.ofPattern("W/MM")
.withLocale(Locale.US);
System.out.println("USA formatter : " + usDateTimeFormatter.format(localDate));
DateTimeFormatter isoDateTimeFormatter = DateTimeFormatter.ofPattern("W/MM");
System.out.println("ISO formatter : " + isoDateTimeFormatter.format(localDate));
Output :
USA formatter : 4/09
ISO formatter : 3/09
class test {
public static void main(String[] args){
Calendar cal = Calendar.getInstance();
cal.set(2016, Calendar.AUGUST, 01);
printDayOFWeek(cal, Calendar.MONDAY, 5);//prints monday on 5th week
}
}
private static void printDayOFWeek(Calendar cal, int day, int whatweek) {
cal.set(Calendar.DAY_OF_WEEK, day);//day = Mon, tue, wed,..etc
cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, -1); //-1 return last week
Date last = cal.getTime();
cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, whatweek);
Date one = cal.getTime();
if(one.before(last) || one.compareTo(last) ==0)
{
System.out.println(whatweek +"WEEK" + cal.getTime());
}
}