Getting the week number for a date (week starting on Wednesday) - java

LocalDate initial = LocalDate.now();
DayOfWeek dayOfWeek = DayOfWeek.WEDNESDAY;
WeekFields weekFields = WeekFields.of(dayOfWeek, 1);
int weekNo = date.get(weekFields.weekOfWeekBasedYear());
System.out.println("Week No"+weekNo);
I am using the above code for date 2018-07-29. I expect week no 30, but I get 31.
What am I missing here to get the result of 30?

If you expected output as according to ISO-8601, where current week is week 30, you'd need to follow this:
Week number according to the ISO-8601 standard, weeks starting on Monday. The first week of the year is the week that contains that year's first Thursday (='First 4-day week').
This is implemented by WeekFields.ISO.
If instead, you want the week to start on WEDNESDAY, you only need to change the minimalDaysInFirstWeek from 1 to 4 (='First 4-day week'):
LocalDate date = LocalDate.now();
WeekFields weekFields = WeekFields.of(DayOfWeek.WEDNESDAY, 4);
int weekNo = date.get(weekFields.weekOfWeekBasedYear());
System.out.println("Week No " + weekNo);

Related

How to select sunday before first monday of the passed month

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 selected date in java?

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.

Not able to Subtract 1 day from New Year date using java(1-1-2100)

I just want to subtract 1 day from New year date in my current scenario.
But while I subtract I get date: 31-0-2100.
Calendar cal = Calendar.getInstance();
cal.set(2100, 1, 1);
cal.add(Calendar.DATE, -1);
String dateStr = ""+cal.get(Calendar.DATE)+
"-"+cal.get(Calendar.MONTH)+"-"+cal.get(Calendar.YEAR);
System.out.println(dateStr);
The actual date should be: 31-12-2099
When you're doing cal.set(2100, 1, 1);, the date you set is actually the first day of February and not January since months are 0 base indexed (0 -> January, ..., 11 -> December).
I would recommend you to use JodaTime which is a far better library to deal with dates and time.
DateTime date = new DateTime(2100, 1, 1, 0, 0, 0);
date = date.minusDays(1);
System.out.println(date.toString("dd-MM-yyyy")); //31-12-2099
Or if you're using java-8, they introduced a brand-new date and time API:
LocalDate date = LocalDate.of(2100, Month.JANUARY, 1);
date = date.minusDays(1);
System.out.println(date.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"))); //31-12-2099
In java the month 0 is January.
So what you got is correct since you're substracting 1 day from February 1st 2100
Notice that the field MONTH is 0-indexed, so the month '1' is actually February and what you are getting: '31-0'2100' is the last day of January.
Source: http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#MONTH
Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.
Implemented using Calendar functionality.
Tested and Executed
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
cal.set(2099, 00, 01);
cal.add(Calendar.DATE, -1);
System.out.println(dateFormat.format(cal.getTime()));
Another solution Formulate the DateTime using the below methods
date.getYear();
date.getDay();
date.getMonth();
Try to pass those arguments into the DateTime.
DateTime date = new DateTime(2100, 1, 1, 0, 0, 0);
date = date.minusDays(1);
System.out.println(date.toString("yyyy-MM-dd"));
Use this instead:
call.add(Calendar.DAY_OF_MONTH, -1)

Creating java date object from year,month,day

int day = Integer.parseInt(request.getParameter("day")); // 25
int month = Integer.parseInt(request.getParameter("month")); // 12
int year = Integer.parseInt(request.getParameter("year")); // 1988
System.out.println(year);
Calendar c = Calendar.getInstance();
c.set(year, month, day, 0, 0);
b.setDob(c.getTime());
System.out.println(b.getDob());
Output is:
1988
Wed Jan 25 00:00:08 IST 1989
I am passing 25 12 1988 but I get 25 Jan 1989. Why?
Months are zero-based in Calendar. So 12 is interpreted as december + 1 month. Use
c.set(year, month - 1, day, 0, 0);
That's my favorite way prior to Java 8:
Date date = new GregorianCalendar(year, month - 1, day).getTime();
I'd say this is a bit cleaner than:
calendar.set(year, month - 1, day, 0, 0);
java.time
Using java.time framework built into Java 8
int year = 2015;
int month = 12;
int day = 22;
LocalDate.of(year, month, day); //2015-12-22
LocalDate.parse("2015-12-22"); //2015-12-22
//with custom formatter
DateTimeFormatter.ofPattern formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate.parse("22-12-2015", formatter); //2015-12-22
If you need also information about time(hour,minute,second) use some conversion from LocalDate to LocalDateTime
LocalDate.parse("2015-12-22").atStartOfDay() //2015-12-22T00:00
Java's Calendar representation is not the best, they are working on it for Java 8. I would advise you to use Joda Time or another similar library.
Here is a quick example using LocalDate from the Joda Time library:
LocalDate localDate = new LocalDate(year, month, day);
Date date = localDate.toDate();
Here you can follow a quick start tutorial.
See JavaDoc:
month - the value used to set the MONTH calendar field. Month value is
0-based. e.g., 0 for January.
So, the month you set is the first month of next year.
Make your life easy when working with dates, timestamps and durations. Use HalDateTime from
http://sourceforge.net/projects/haldatetime/?source=directory
For example you can just use it to parse your input like this:
HalDateTime mydate = HalDateTime.valueOf( "25.12.1988" );
System.out.println( mydate ); // will print in ISO format: 1988-12-25
You can also specify patterns for parsing and printing.

How to find week of the month

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());
}
}

Categories

Resources