Find Out The Date For First Sunday/monday Etc Of The Month
I want to detect date of First Sunday/Monday of first/second week in every month in java? How can I achieve it? I have checked Calendar class as well as Date class in java but not
Solution 1:
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MMM/dd/YYYY");
calendar.set(Calendar.MONTH,Calendar.JUNE);
calendar.set(Calendar.DAY_OF_MONTH,1);
int day = (Calendar.TUESDAY-calendar.get(Calendar.DAY_OF_WEEK));
if(day<0){
calendar.add(Calendar.DATE,7+(day));
}else{
calendar.add(Calendar.DATE,day);
}
System.out.println("First date is "+sdf.format(calendar.getTime()));`enter code here`
Solution 2:
This will Give you First Saturday Of every month Of a Year of system date... u can also get other replace saturday with any other day
Invented By HK2 and Hemant
import java.util.Calendar;
import java.util.GregorianCalendar
classDemo{
SimpleDateFormatformat=newSimpleDateFormat("dd-MMM-yyyy");
StringDATE_FORMAT="yyyy MM dd";
SimpleDateFormatsdf=newSimpleDateFormat(DATE_FORMAT);
Calendarc1= Calendar.getInstance();
String y=sdf.format(c1.getTime());
String years=y.substring(0,4);
int year=Integer.parseInt(years);
Calendarcal=newGregorianCalendar(year, Calendar.JANUARY, 1);
for (inti=0, inc = 1; i <366 && cal.get(Calendar.YEAR) == year; i+=inc) {
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
String frm="";
frm=format.format(cal.getTime());
// System.out.println("the value of the saturday is "+format.format(cal.getTime()));
cal.add(Calendar.MONTH,1);
cal.set(Calendar.DAY_OF_MONTH, 1);
}
else {
cal.add(Calendar.DAY_OF_MONTH, 1);
}
}
}
Solution 3:
Java.time
Using java.time
library built into Java 8:
import java.time.{DayOfWeek, LocalDate}
import java.time.temporal.TemporalAdjusters.firstInMonth
val now = LocalDate.now() # 2015-11-23
val firstMonday = now.`with`(firstInMonth(DayOfWeek.MONDAY)) # 2015-11-02 (Monday)
You may choose any day from java.time.DayOfWeek.{MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY}
.
If you need to add time information, you may use any available LocalDate
to LocalDateTime
conversion like
firstMonday.atStartOfDay() # 2015-11-02T00:00
Solution 4:
The simplest method of doing it with Java 8 is:
LocalDate firstSundayOfNextMonth = LocalDate
.now()
.with(firstDayOfNextMonth())
.with(nextOrSame(DayOfWeek.MONDAY));
Solution 5:
You can get the day of the week for a specific date in Java using Calendar
class as discussed here:
How to determine day of week by passing specific date?
You can then loop over the dates in your range to find the first instance of Sunday and the second instance of Monday.
Post a Comment for "Find Out The Date For First Sunday/monday Etc Of The Month"