How can i learn next wednesday, monday in a week? Forexample Today 06.02.2009 next Monday 09.02.2009 or wednesday 11.02.2009 there is any algorithm?
i need :
which day monday in comingweek?
findDay("Monday")
it must return 09.02.2009
=====================================================
findDay("Tuesday")
it must return 10.02.2009
public static DateTime GetNextDayDate(DayOfWeek day) {
DateTime now = DateTime.Now;
int dayDiff = (int)(now.DayOfWeek - day);
if (dayDiff <= 0) dayDiff += 7;
return now.AddDays(dayDiff);
}
DateTime now = DateTime.Now;
DateTime nextMonday = now.AddDays((int)now.DayOfWeek - (int)DayOfWeek.Monday);
Hum it seems that I answered too quickly. Actually there are more checking to do. Have a look at nobugz or peterchen answers.
I found a simpler solution:
DayOfWeek is an enum, as: Monday=1, Tuesday=2, etc.
So, to get next Monday (from today) you should use:
DateTime.Today.AddDays(8-(int)DateTime.Today.DayOfWeek)
where "8" is next week's Monday(according to the enum-> 1+7).
Replace the 8 for a 10 (i.e. Wednesday, 3+7) and you'll get next week's Wednesday, and so on...
Like Tyalis, but some extra checking is required:
int daysUntilMonday = ((int)DayOfWeek.Monday - (int)today.DayOfWeek;
if (daysUntilMonday <= 0)
daysUntilMonday += 7;
Monday = DateTime.Now.AddDays(daysUntilMonday);
Just iterate a bit:
DateTime baseDate = ...;
DayOfWeek requiredDayOfWeek = ...;
while(baseDate.DayOfWeek != requiredDayOfWeek)
baseDate = baseDate.AddDays(1);
You can also write an extension method if those are available:
static Next(this DateTime date, DayOfWeek requiredDayOfWeek) { ... }
and you'll get pretty syntax: today.Next(DayOfWeek.Saturday).
Related
I was looking for a way to fetch the same day of the current week as a year ago. For example, today is:
August 10th 2022 - Wednesday.
Assume this is the check-in date, the check-out date I expect to get is:
August 11, 2021 - Wednesday.
Because it's the same day (Wednesday) as last year. But I need to take leap years into account, so I need to see if the current year is a leap year and if it is, if it has passed the 29th of February, the same with the date last year.
How to do this using .net core ? I thought of something like:
private DateTime GetDayOneYearBefore()
{
if(DateTime.IsLeapYear(DateTime.Today.Year) && DateTime.Today.Month > 2){
return DateTime.Today.AddDays(-365);
}
else if(DateTime.IsLeapYear(DateTime.Today.Year) && DateTime.Today.Month <= 2){
return DateTime.Today.AddDays(-364);
}
}
Since you mention the "same week" I suppose you want to get the same day of the week in the same week number?
If so, you can do the following:
// In the System.DayOfWeek enum Sunday = 0, while Monday = 1
// This converts DateTime.DayOfWeek to a range where Monday = 0 and Sunday = 6
static int DayOfWeek(DateTime dt)
{
const int weekStart = (int)System.DayOfWeek.Monday;
const int daysInAWeek = 7;
return (daysInAWeek - (weekStart - (int)dt.DayOfWeek)) % daysInAWeek;
}
var calendar = CultureInfo.CurrentCulture.Calendar;
var weekNum = calendar.GetWeekOfYear(DateTime.Today, CalendarWeekRule.FirstFourDayWeek, System.DayOfWeek.Monday);
var todayLastYear = DateTime.Today.AddYears(-1);
var lastYearWeekNum = calendar.GetWeekOfYear(todayLastYear, CalendarWeekRule.FirstFourDayWeek, System.DayOfWeek.Monday);
var sameWeekLastYear = todayLastYear.AddDays(7 * (weekNum - lastYearWeekNum));
var sameDaySameWeekLastYear = sameWeekLastYear.AddDays(DayOfWeek(DateTime.Today) - DayOfWeek(sameWeekLastYear));
As you might notice there's a little convertion method, since I normally work with Monday being the first day of the week. If you prefer a different day to be the first day of the week, simply replace System.DayOfWeek.Monday with which ever day you'd like.
See this fiddle for a test run.
I want to get date of specific day of a given week. The week is decided by the entered date.
For example, if I want the Friday of these dates:
06/27/2018
07/04/2018
07/07/2018
I expect as outcome:
06/29/2018
07/06/2018
07/06/2018
Here, week is defined as Monday to Sunday.
You can do this with some clever maths based on the DayOfWeek:
public DateTime GetDay(DateTime source, DayOfWeek dayOfWeek,
DayOfWeek weekStartsOn = DayOfWeek.Monday)
{
var offset = (int)source.DayOfWeek - (int)weekStartsOn;;
if(offset < 0)
{
offset = offset + 7;
}
return source.AddDays(-offset + (int)dayOfWeek - (int)weekStartsOn);
}
And use it like this:
var someDate = ...; //Get a date from somewhere
var friday = GetDay(someDate, DayOfWeek.Friday);
var monday = GetDay(someDate, DayOfWeek.Monday);
And if your week starts on a Sunday, just use the optional third parameter, for example:
var friday = GetDay(someDate, DayOfWeek.Friday, DayOfWeek.Sunday);
A modification of the current version of DavidG's answer:
static DateTime GetDay(DateTime source, DayOfWeek dayOfWeek)
{
const int offsetSinceMondayIsFirstDayOfWeek = 7 - (int)DayOfWeek.Monday;
return source.AddDays(((int)dayOfWeek + offsetSinceMondayIsFirstDayOfWeek) % 7
- ((int)source.DayOfWeek + offsetSinceMondayIsFirstDayOfWeek) % 7);
}
This takes into account that the asker considers Monday to be the first day of the week. If you want Saturday as the first day of week, just replace Monday with Saturday above.
In the special case where you consider Sunday the first day of the week, it reduces to DavidG's original method:
static DateTime GetDay(DateTime source, DayOfWeek dayOfWeek)
{
return source.AddDays((int)dayOfWeek - (int)source.DayOfWeek);
}
because the DayOfWeek enum type of the BCL already "wraps around" between Saturday (= 6) and Sunday (= 0).
On http://chartsbin.com/view/41671 there is a world map that apparently shows what day of week is considered the first day of the week in different regions.
public void TestMethod1 ( )
{
DateTime date = DateTime.Now;
DateTime friday = date.AddDays( (int)DayOfWeek.Friday - (int)date.DayOfWeek );
Console.WriteLine( friday.ToString( ) );
}
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
DateTime dateValue = new DateTime(2008, 6, 11);
Console.WriteLine(dateValue.ToString("ddd",
new CultureInfo("fr-FR")));
}
}
This question already has answers here:
How can I get the DateTime for the start of the week?
(34 answers)
Closed 8 years ago.
I was wondering if you guys know how to get the date of currents week's monday based on todays date?
i.e 2009-11-03 passed in and 2009-11-02 gets returned back
/M
This is what i use (probably not internationalised):
DateTime input = //...
int delta = DayOfWeek.Monday - input.DayOfWeek;
DateTime monday = input.AddDays(delta);
The Pondium answer can search Forward in some case. If you want only Backward search I think it should be:
DateTime input = //...
int delta = DayOfWeek.Monday - input.DayOfWeek;
if(delta > 0)
delta -= 7;
DateTime monday = input.AddDays(delta);
Something like this would work
DateTime dt = DateTime.Now;
while(dt.DayOfWeek != DayOfWeek.Monday) dt = dt.AddDays(-1);
I'm sure there is a nicer way tho :)
public static class DateTimeExtension
{
public static DateTime GetFirstDayOfWeek(this DateTime date)
{
var firstDayOfWeek = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
while (date.DayOfWeek != firstDayOfWeek)
{
date = date.AddDays(-1);
}
return date;
}
}
International here. I think as extension it can be more useful.
What about:
CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek
Why don't use native solution?
var now = System.DateTime.Now;
var result = now.AddDays(-((now.DayOfWeek - System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek + 7) % 7)).Date;
Probably will return you with Monday. Unless you are using a culture where Monday is not the first day of the week.
Try this:
public DateTime FirstDayOfWeek(DateTime date)
{
var candidateDate=date;
while(candidateDate.DayOfWeek!=DayOfWeek.Monday) {
candidateDate=candidateDate.AddDays(-1);
}
return candidateDate;
}
EDIT for completeness: overload for today's date:
public DateTime FirstDayOfCurrentWeek()
{
return FirstDayOfWeek(DateTime.Today);
}
I have something odd requirement. I have Current Date and List of Week Days. And I want next all possible date till the target date.
For i.e. Today, its 22-04-2014 And Tuesday. Target date is 15-05-2014I have 2 week days, Monday and Thursday. So code should find near by Week Day, which will be Thursday here. So It should return date of Thursday which is 24-04-2014. Now, next turn is of Monday which comes from List. So now, It should return date of Monday which is 28-04-2014.
It should keep repeating till the target date.
So, final result will be
24-04-2014,
28-04-2014,
1-05-2014,
5-05-2014,
8-05-2014,
12-05-2014
Please help me to get this type of result. Here, Monday and Thursday is not fixed. It can be any Day and any number of Day.
Update : Link to the working example - Example
You can try this code, i have tested it and working correctly
private List<DateTime> ProcessDate(DateTime dtStartDate, DateTime targetDate)
{
DateTime dtLoop = dtStartDate;
//dtRequiredDates to hold required dates
List<DateTime> dtRequiredDates = new List<DateTime>();
for (int i = dtStartDate.DayOfYear; i < targetDate.DayOfYear; i++)
{
if (dtLoop.DayOfWeek == DayOfWeek.Monday || dtLoop.DayOfWeek == DayOfWeek.Thursday)
{
dtRequiredDates.Add(dtLoop);
}
dtLoop = dtLoop.AddDays(1);
}
return dtRequiredDates;
}
You may have to enhance this codes so that it doesn't throw any exception based on the requirement.
UPDATE 2:
You can have another method which will accept the days of week as follows
private List<DateTime> ProcessDate(DateTime dtStartDate, DateTime targetDate, List<DayOfWeek> daysOfWeek)
{
DateTime dtLoop = dtStartDate;
List<DateTime> dtRequiredDates = new List<DateTime>();
for (int i = dtStartDate.DayOfYear; i < targetDate.DayOfYear; i++)
{
foreach (DayOfWeek day in daysOfWeek)
{
if (dtLoop.DayOfWeek == day)
{
dtRequiredDates.Add(dtLoop);
}
}
dtLoop = dtLoop.AddDays(1);
}
return dtRequiredDates;
}
Here is the Example
Hence you can pass any number of week days as you wish.
Hope this helps
You could try something like this:
List<DayOfWeek> listOfDays = new List<DayOfWeek>{DayOfWeek.Monday, DayOfWeek.Thursday};
var end = new DateTime(2014,05,15);
var day = DateTime.Now.Date;
while (day < end)
{
day.AddDays(1); // adds +1 days to "day"
if (listOfDays.Contains(day.DayOfWeek)) Console.WriteLine(day.Date.ToString());
}
(I can't test the code right now, so maybe you need to modify a little ;-)
I have a requirement where i want to calculate last Date of a given day based on today's Date. For example I have a method
DateTime GetDate(DateTime now, DayOfWeek dayOfWeek)
{
//Logic goes here
}
For e.g
If i pass friday in dayofWeek and today is Monday, then it should
return me last friday date.
If i pass friday and today is friday then same date should be
return.
Conditions:
I just want to use formula to calculate the date.
Don't want anything to be assumed or hard-coded.
I don't want to use if...else.
You can work out how many days to subtract by comparing the current day of week with the target one, wrapping round in case it's negative:
static DateTime GetDate(DateTime now, DayOfWeek dayOfWeek)
{
// Number of days to subtract, e.g. 1 for "today is Friday, we want Thursday"
// The ((...) + 7) % 7 part is to handle wrap-around for negative values.
int daysDifference = ((now.DayOfWeek - dayOfWeek) + 7) % 7;
return now.AddDays(-daysDifference);
}
Or using Noda Time (my date/time API which allow for a cleaner representation of "just a date" etc):
static LocalDate GetDate(LocalDate today, IsoDayOfWeek dayOfWeek)
{
return today.IsoDayOfWeek == dayOfWeek ? today : today.Previous(dayOfWeek);
}
Ok,
DateTime GetDate(DateTime now, DayOfWeek dayOfWeek)
{
var day = new TimeSpan(1, 0, 0, 0);
var result = now;
while(result.DayOfWeek != dayOfWeek)
{
result = result.Substract(day)
}
return result;
}
private static DateTime GetDate(DateTime todayDate, DayOfWeek dayofweek)
{
while (todayDate.DayOfWeek != dayofweek)
{
todayDate = todayDate.AddDays(-1);
}
return todayDate;
}