Compute the Datetime of an Upcoming Weekday

Compute the DateTime of an upcoming weekday

As I've mentioned in the comments, there are various things you could mean by "next Tuesday", but this code gives you "the next Tuesday to occur, or today if it's already Tuesday":

DateTime today = DateTime.Today;
// The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
int daysUntilTuesday = ((int) DayOfWeek.Tuesday - (int) today.DayOfWeek + 7) % 7;
DateTime nextTuesday = today.AddDays(daysUntilTuesday);

If you want to give "a week's time" if it's already Tuesday, you can use:

// This finds the next Monday (or today if it's Monday) and then adds a day... so the
// result is in the range [1-7]
int daysUntilTuesday = (((int) DayOfWeek.Monday - (int) today.DayOfWeek + 7) % 7) + 1;

... or you could use the original formula, but from tomorrow:

DateTime tomorrow = DateTime.Today.AddDays(1);
// The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
int daysUntilTuesday = ((int) DayOfWeek.Tuesday - (int) tomorrow.DayOfWeek + 7) % 7;
DateTime nextTuesday = tomorrow.AddDays(daysUntilTuesday);

EDIT: Just to make this nice and versatile:

public static DateTime GetNextWeekday(DateTime start, DayOfWeek day)
{
// The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
int daysToAdd = ((int) day - (int) start.DayOfWeek + 7) % 7;
return start.AddDays(daysToAdd);
}

So to get the value for "today or in the next 6 days":

DateTime nextTuesday = GetNextWeekday(DateTime.Today, DayOfWeek.Tuesday);

To get the value for "the next Tuesday excluding today":

DateTime nextTuesday = GetNextWeekday(DateTime.Today.AddDays(1), DayOfWeek.Tuesday);

How to get date of next coming specific day in C#

Using the following

public int CalculateOffset(DayOfWeek current, DayOfWeek desired) {
// f( c, d ) = [7 - (c - d)] mod 7
// f( c, d ) = [7 - c + d] mod 7
// c is current day of week and 0 <= c < 7
// d is desired day of the week and 0 <= d < 7
int c = (int)current;
int d = (int)desired;
int offset = (7 - c + d) % 7;
return offset == 0 ? 7 : offset;
}

You can calculate how far you are from the desired day and then add that to the current date

DateTime now = DateTime.Now.Date;
int offset = CalculateOffset(now.DayOfWeek, DayOfWeek.Friday);
DateTime nextFriday = now.AddDays(offset);

How do I get the day of week given a date?

Use weekday():

>>> import datetime
>>> datetime.datetime.today()
datetime.datetime(2012, 3, 23, 23, 24, 55, 173504)
>>> datetime.datetime.today().weekday()
4

From the documentation:

Return the day of the week as an integer, where Monday is 0 and Sunday is 6.

How to calculate next Friday?

A certain improvement on @taymon`s answer:

today = datetime.date.today()
friday = today + datetime.timedelta( (4-today.weekday()) % 7 )

4 is Friday's weekday (0 based, counting from Monday).

( (4-today.weekday()) % 7) is the number of days till next friday (% is always non-negative).

After seeing @ubuntu's answer, I should add two things:

1. I'm not sure if Friday=4 is universally true. Some people start their week on Sunday.

2. On Friday, this code returns the same day. To get the next, use (3-today.weekday())%7+1. Just the old x%n to ((x-1)%n)+1 conversion.

Get next date from weekday in JavaScript

Just adding 7 doesn't solve the problem.

The below function will give you the next day of the week.

function nextDay(x){
var now = new Date();
now.setDate(now.getDate() + (x+(7-now.getDay())) % 7);
return now;
}

Finding the date of the next Saturday


>>> from datetime import datetime, timedelta
>>> d = datetime.strptime('2013-05-27', '%Y-%m-%d') # Monday
>>> t = timedelta((12 - d.weekday()) % 7)
>>> d + t
datetime.datetime(2013, 6, 1, 0, 0)
>>> (d + t).strftime('%Y-%m-%d')
'2013-06-01'

I use (12 - d.weekday()) % 7 to compute the delta in days between given day and next Saturday because weekday is between 0 (Monday) and 6 (Sunday), so Saturday is 5. But:

  • 5 and 12 are the same modulo 7 (yes, we have 7 days in a week :-) )
  • so 12 - d.weekday() is between 6 and 12 where 5 - d.weekday() would be between 5 and -1
  • so this allows me not to handle the negative case (-1 for Sunday).

Here is a very simple version (no check) for any weekday:

>>> def get_next_weekday(startdate, weekday):
"""
@startdate: given date, in format '2013-05-25'
@weekday: week day as a integer, between 0 (Monday) to 6 (Sunday)
"""
d = datetime.strptime(startdate, '%Y-%m-%d')
t = timedelta((7 + weekday - d.weekday()) % 7)
return (d + t).strftime('%Y-%m-%d')

>>> get_next_weekday('2013-05-27', 5) # 5 = Saturday
'2013-06-01'

getting the date for next weekday

You should use actual date objects, not strings:

>>> import datetime
>>> today = datetime.date.today()
>>> if today.isoweekday() in set((6, 7)):
today += datetime.timedelta(days=today.isoweekday() % 5)


>>> today
datetime.date(2014, 9, 30)

Note that isoweekday is 1 (Monday) to 7 (Sunday), whereas weekday is 0 to 6.


Also, note that your logic currently adds one day to Saturday and two days to Sunday, which isn't correct - I think you want:

>>> if today.isoweekday() in set((6, 7)):
today += datetime.timedelta(days=8 - today.isoweekday())

For example:

>>> day = datetime.date(2014, 10, 4)
>>> day
datetime.date(2014, 10, 4) # Saturday
>>> if day.isoweekday() in set((6, 7)):
day += datetime.timedelta(days=8 - day.isoweekday())


>>> day
datetime.date(2014, 10, 6) # Monday

Find the date for the first Monday after a given date


import datetime
def next_weekday(d, weekday):
days_ahead = weekday - d.weekday()
if days_ahead <= 0: # Target day already happened this week
days_ahead += 7
return d + datetime.timedelta(days_ahead)

d = datetime.date(2011, 7, 2)
next_monday = next_weekday(d, 0) # 0 = Monday, 1=Tuesday, 2=Wednesday...
print(next_monday)

Get next week dates (C#)

you can try something like this:

//first get next monday (thanks to this answer: https://stackoverflow.com/a/6346190/6170890 )
DateTime today = DateTime.Today;
int daysUntilMonday = ((int)DayOfWeek.Monday - (int)today.DayOfWeek + 7) % 7;
//if today is monday, add seven days
if (daysUntilMonday == 0)
daysUntilMonday = 7;

//create DateTime variables for next week's beginning and end
DateTime nextWeekMonday = today.AddDays(daysUntilMonday);
DateTime nextWeekSunday = nextWeekMonday.AddDays(6);

//finally, do your select
var items = db.Appointments.Where(x => x.Date >= nextWeekMonday && x.Date <= nextWeekSunday)
.Select(x => new
{
title = x.Title,
time = x.Start_appointment
}).ToList();
return Json(items, JsonRequestBehavior.AllowGet);

Calculate the Week day of months from given date?

Just add 4 weeks to input date, add 7 more days if necessary:

static DateTime GetNextDate(DateTime d1)
{
System.Diagnostics.Debug.Assert(d1.Day <= 28, "Behavior not described");
DateTime d2 = d1.AddDays(28);
// the following evaluates to 1 for 1-7, 2 for 8-14, etc
int n1 = (d1.Day - 1) / 7 + 1;
int n2 = (d2.Day - 1) / 7 + 1;
if (n2 != n1)
{
d2 = d2.AddDays(7);
}
return d2;
}

Sample input and output:

Thu 2018-Mar-01 > Thu 2018-Apr-05
Fri 2018-Mar-02 > Fri 2018-Apr-06
Sat 2018-Mar-03 > Sat 2018-Apr-07
Sun 2018-Mar-04 > Sun 2018-Apr-01
Mon 2018-Mar-05 > Mon 2018-Apr-02
Tue 2018-Mar-06 > Tue 2018-Apr-03
Wed 2018-Mar-07 > Wed 2018-Apr-04
Thu 2018-Mar-08 > Thu 2018-Apr-12
Fri 2018-Mar-09 > Fri 2018-Apr-13
Sat 2018-Mar-10 > Sat 2018-Apr-14
Sun 2018-Mar-11 > Sun 2018-Apr-08
Mon 2018-Mar-12 > Mon 2018-Apr-09
Tue 2018-Mar-13 > Tue 2018-Apr-10
Wed 2018-Mar-14 > Wed 2018-Apr-11
Thu 2018-Mar-15 > Thu 2018-Apr-19
Fri 2018-Mar-16 > Fri 2018-Apr-20
Sat 2018-Mar-17 > Sat 2018-Apr-21
Sun 2018-Mar-18 > Sun 2018-Apr-15
Mon 2018-Mar-19 > Mon 2018-Apr-16
Tue 2018-Mar-20 > Tue 2018-Apr-17
Wed 2018-Mar-21 > Wed 2018-Apr-18
Thu 2018-Mar-22 > Thu 2018-Apr-26
Fri 2018-Mar-23 > Fri 2018-Apr-27
Sat 2018-Mar-24 > Sat 2018-Apr-28
Sun 2018-Mar-25 > Sun 2018-Apr-22
Mon 2018-Mar-26 > Mon 2018-Apr-23
Tue 2018-Mar-27 > Tue 2018-Apr-24
Wed 2018-Mar-28 > Wed 2018-Apr-25


Related Topics



Leave a reply



Submit