Get current week start and end date in Java - (MONDAY TO SUNDAY)
Updated answer using Java 8Using Java 8 and keeping the same principle as before (the first day of the week depends on your Locale
), you should consider using the following:
Obtain the first and last DayOfWeek
for a specific Locale
final DayOfWeek firstDayOfWeek = WeekFields.of(locale).getFirstDayOfWeek();
final DayOfWeek lastDayOfWeek = DayOfWeek.of(((firstDayOfWeek.getValue() + 5) % DayOfWeek.values().length) + 1);
Query for this week's first and last day
LocalDate.now(/* tz */).with(TemporalAdjusters.previousOrSame(firstDayOfWeek)); // first day
LocalDate.now(/* tz */).with(TemporalAdjusters.nextOrSame(lastDayOfWeek)); // last day
DemonstrationConsider the following class
:
private static class ThisLocalizedWeek {
// Try and always specify the time zone you're working with
private final static ZoneId TZ = ZoneId.of("Pacific/Auckland");
private final Locale locale;
private final DayOfWeek firstDayOfWeek;
private final DayOfWeek lastDayOfWeek;
public ThisLocalizedWeek(final Locale locale) {
this.locale = locale;
this.firstDayOfWeek = WeekFields.of(locale).getFirstDayOfWeek();
this.lastDayOfWeek = DayOfWeek.of(((this.firstDayOfWeek.getValue() + 5) % DayOfWeek.values().length) + 1);
}
public LocalDate getFirstDay() {
return LocalDate.now(TZ).with(TemporalAdjusters.previousOrSame(this.firstDayOfWeek));
}
public LocalDate getLastDay() {
return LocalDate.now(TZ).with(TemporalAdjusters.nextOrSame(this.lastDayOfWeek));
}
@Override
public String toString() {
return String.format( "The %s week starts on %s and ends on %s",
this.locale.getDisplayName(),
this.firstDayOfWeek,
this.lastDayOfWeek);
}
}
We can demonstrate its usage as follows:
final ThisLocalizedWeek usWeek = new ThisLocalizedWeek(Locale.US);
System.out.println(usWeek);
// The English (United States) week starts on SUNDAY and ends on SATURDAY
System.out.println(usWeek.getFirstDay()); // 2018-01-14
System.out.println(usWeek.getLastDay()); // 2018-01-20
final ThisLocalizedWeek frenchWeek = new ThisLocalizedWeek(Locale.FRANCE);
System.out.println(frenchWeek);
// The French (France) week starts on MONDAY and ends on SUNDAY
System.out.println(frenchWeek.getFirstDay()); // 2018-01-15
System.out.println(frenchWeek.getLastDay()); // 2018-01-21
Original Java 7 answer (outdated)Simply use:
c.setFirstDayOfWeek(Calendar.MONDAY);
Explanation:
Right now, your first day of week is set on Calendar.SUNDAY
. This is a setting that depends on your Locale
.
Thus, a better alternative would be to initialise your Calendar
specifying the Locale
you're interested in.
For example:
Calendar c = GregorianCalendar.getInstance(Locale.US);
... would give you your current output, while:
Calendar c = GregorianCalendar.getInstance(Locale.FRANCE);
... would give you your expected output.
Get the week start and end date given a current date and week start
Try this (pseudo-code):
// How many days gone after reference date (a known week-start date)
daysGone = today - referenceDate;
// A new week starts after each 7 days
dayOfWeek = daysGone % 7;
// Now, we know today is which day of the week.
// We can find start & end days of this week with ease
weekStart = today - dayOfWeek;
weekEnd = weekStart + 6;
Now, we can shorten all of this to two lines:
weekStart = today - ((today - referenceDate) % 7);
weekEnd = weekStart + 6;
Note that we subtracted date values like integers to show algorithm. You have to write your java code properly.
How to get first and last day of the current week in JavaScript
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();
firstday
"Sun, 06 Mar 2011 12:25:40 GMT"
lastday
"Sat, 12 Mar 2011 12:25:40 GMT"
This works for firstday = sunday of this week and last day = saturday for this week. Extending it to run Monday to sunday is trivial.
Making it work with first and last days in different months is left as an exercise for the user
Getting the start and the end date of a week using java calendar class
Some code how to do it with the Calendar
object. I should also mention joda time library as it can help you many of Date/Calendar
problems.
public static void main(String[] args) {
// set the date
Calendar cal = Calendar.getInstance();
cal.set(2011, 10 - 1, 12);
// "calculate" the start date of the week
Calendar first = (Calendar) cal.clone();
first.add(Calendar.DAY_OF_WEEK,
first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
// and add six days to the end date
Calendar last = (Calendar) first.clone();
last.add(Calendar.DAY_OF_YEAR, 6);
// print the result
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(df.format(first.getTime()) + " -> " +
df.format(last.getTime()));
}
Retrieve current week's Monday's date
I would strongly recommend using Joda Time instead (for all your date/time work, not just this):
// TODO: Consider time zones, calendars etc
LocalDate now = new LocalDate();
LocalDate monday = now.withDayOfWeek(DateTimeConstants.MONDAY);
System.out.println(monday);
Note that as you've used Monday here, which is the first day of the week in Joda Time, this will always return an earlier day (or the same day). If you chosen Wednesday (for example), then it would advance to Wednesday from Monday or Tuesday. You can always add or subtract a week if you need "the next Wednesday" or "the previous Wednesday".
EDIT: If you really want to use java.util.Date/Calendar, you can use:
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Date " + c.getTime());
You can use Calendar.setFirstDayOfWeek
to indicate whether a week is Monday-Sunday or Sunday-Saturday; I believe setting the day of the week will stay within the current week - but test it.
java - to get the start date and end date of each week for the given month
I get the answer with the following code
List<List<String>> getNumberOfWeeks(int year, int month) {
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
List<List<String>> weekdates = new ArrayList<List<String>>();
List<String> dates;
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, 1);
while (c.get(Calendar.MONTH) == month) {
dates = new ArrayList<String>();
while (c.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
c.add(Calendar.DAY_OF_MONTH, -1);
}
dates.add(format.format(c.getTime()));
c.add(Calendar.DAY_OF_MONTH, 6);
dates.add(format.format(c.getTime()));
weekdates.add(dates);
c.add(Calendar.DAY_OF_MONTH, 1);
}
System.out.println(weekdates);
return weekdates;
}
How to get date of all days in past week?
Can you try different approach? like pass today's date to sql procedure and filter last 7 days at query level with where clause?
say where date is <= today-7
Related Topics
Field Required a Bean Which Could Not Be Found in Springboot
How to Get All Members of Ad Group Via Ldap in Java
Jpa:How to Convert a Native Query Result Set to Pojo Class Collection
Eclipse Console Not Showing Output
How to Go About Adding an Image into a Java Project With Eclipse
How to Avoid Nullpointerexception With an Empty Cell Using Poi
Jackson Jsonmappingexception: Can Not Deserialize Instance
How to Clean Old Dependencies from Maven Repositories
How to Remove Trailing Zeros from a Double
Maven Build Cannot Find Symbol When Accessing Project Lombok Annotated Methods,
Regular Expression for Excluding Special Characters
Use String.Split() With Multiple Delimiters
Returning Json Object as Response in Spring Boot
Spring Data JPA and Parameters That Can Be Null
How to Send Date in Rest API in Post Method
How to Replace Multiple Words in a Single String in Java
Intellij Incorrectly Saying No Beans of Type Found for Autowired Repository