Get the Week Start and End Date Given a Current Date and Week Start

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

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.

Get current week start and end date in Java - (MONDAY TO SUNDAY)

Updated answer using Java 8

Using 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

Demonstration

Consider 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.

How to get current week start date ( Monday ) and End Date ( Sunday) in R

You can use lubridate's floor_date and ceiling_date with unit as "week". By default week starts on a Sunday in lubridate so to get start date as Monday we need to add 1 in floor_date.

library(lubridate)
todays_date <- as.Date('2020-07-18')
floor_date(todays_date, 'week') + 1
#[1] "2020-07-13"

ceiling_date(todays_date, 'week')
#[1] "2020-07-19"

How to get the week number, start date and end date of Compelete year in SQL Server?

If you are interested in 2019 only, then the following code will produce exactly what you are looking for:

DECLARE @weekNum INT = 1;

WITH Weeks AS (
SELECT @weekNum AS WeekNo
UNION ALL
SELECT WeekNo + 1 FROM Weeks WHERE WeekNo + 1 <= 53
)
SELECT WeekNo,
CASE
WHEN WeekStartDate < '2019-01-01' THEN CONVERT(DATE, '2019-01-01')
ELSE CONVERT(DATE, WeekStartDate)
END AS WeekStartDate,
CASE
WHEN WeekEndDate > '2019-12-31' THEN CONVERT(DATE, '2019-12-31')
ELSE CONVERT(DATE, WeekEndDate)
END AS WeekEndDate
FROM (
SELECT WeekNo,
DATEADD(WEEK, WeekNo - 1, '2018-12-30') AS WeekStartDate,
DATEADD(WEEK, WeekNo - 1, '2019-01-05') AS WeekEndDate
FROM Weeks
) a

OUTPUT:

WeekNo  WeekStartDate   WeekEndDate
1 2019-01-01 2019-01-05
2 2019-01-06 2019-01-12
3 2019-01-13 2019-01-19
4 2019-01-20 2019-01-26
5 2019-01-27 2019-02-02
6 2019-02-03 2019-02-09
7 2019-02-10 2019-02-16
8 2019-02-17 2019-02-23
...
51 2019-12-15 2019-12-21
52 2019-12-22 2019-12-28
53 2019-12-29 2019-12-31

Edit following OP comment about variable start and end dates

Following OP's comment about varying start and end dates, I've revisited the code and made it such that is can work between any two dates:

DECLARE @startDate DATE = CONVERT(DATE, '2019-01-01');
DECLARE @endDate DATE = CONVERT(DATE, '2019-12-31');
DECLARE @weekNum INT = 1;

WITH Weeks AS (
SELECT @weekNum AS WeekNo
UNION ALL
SELECT WeekNo + 1 FROM Weeks WHERE WeekNo + 1 <= DATEDIFF(WEEK, @StartDate, @EndDate) + 1
)
SELECT WeekNo,
CASE
WHEN WeekStartDate < @startDate THEN @startDate
ELSE CONVERT(DATE, WeekStartDate)
END AS WeekStartDate,
CASE
WHEN WeekEndDate > @endDate THEN @endDate
ELSE CONVERT(DATE, WeekEndDate)
END AS WeekEndDate
FROM (
SELECT WeekNo,
DATEADD(WEEK, WeekNo - 1, OffsetStartDate) AS WeekStartDate,
DATEADD(WEEK, WeekNo - 1, OffsetEndDate) AS WeekEndDate
FROM Weeks
INNER JOIN (
SELECT CASE
WHEN DATEPART(WEEKDAY, @startDate) = 1 THEN @startDate
ELSE DATEADD(DAY, 1 - DATEPART(WEEKDAY, @startDate), @startDate)
END AS OffsetStartDate,
CASE
WHEN DATEPART(WEEKDAY, @startDate) = 1 THEN DATEADD(DAY, 6, @startDate)
ELSE DATEADD(DAY, 7 - DATEPART(WEEKDAY, @startDate), @startDate)
END AS OffsetEndDate
) a ON 1 = 1
) a

Simply modify @startDate and @endDate to reflect the desired start and end dates. The format of the string is YYYY-MM-DD.

This will output a variable number of weeks between the two dates, starting and ending on the specified date (creating partial weeks as needed). Hopefully, as per the requirement.

Get Week Start and End Dates

Tweaked OP version a bit

Declare @fromDate date;
DECLARE @date date = GETUTCDATE();
declare @m int = month(@date);
-- -2 to shift start of week to Saturday
-- -5 to shift start to a previous month
SET @fromDate = DATEADD(week, DATEDIFF(week, 0, @date) - 5, 0) -2;
-- 11 weeks to cover month of interest fo sure
with t as (
select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) t(n) )
, dates as (
select [DateS] = dateadd(week, n, @fromdate)
from t
)
-- take current month only
select [DateS], dateadd(dd, 6, [DateS]) [DateE]
from dates
where @m in (month([DateS]), month(dateadd(dd, 6, [DateS])));


Related Topics



Leave a reply



Submit