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);
}
Related
I have application that needs to be run on working days, and within working hours.
In application configuration, I've set start time in format
Monday-Friday
9:00AM-5:30PM
Now, I have a problem how to check if current day is within day boundare is (for the time is easy - parse time with DateTime.ParseExact and simple branch will do), but I don't know how to parse days.
I've tried with:
DayOfWeek day = DateTime.Now.DayOfWeek;
if (day >= (DayOfWeek)Enum.Parse(typeof(DayOfWeek), sr.start_day) &&
day <= (DayOfWeek)Enum.Parse(typeof(DayOfWeek), sr.end_day))
{ /* OK */ }
sr.start_day and sr.end_day are strings
but the problem occurred during weekend testing - apparently, in DayOfWeek enum, Sunday is first day of the week (refering to the comments on MSDN page
I suppose I could do some gymnastics with current code, but I am looking for the most readable code available.
Edit
Sorry for the misunderstanding - working days are not from Monday to Friday - they are defined as strings in config file, and they can be even from Friday to Saturday - which breaks my original code.
if ((day >= DayOfWeek.Monday) && (day <= DayOfWeek.Friday))
{
// action
}
From Hans Passant's comment on my original question:
Just add 7 to the end day if it is less than the start day. Similarly,
add 7 to day if it is less than the start day.
DayOfWeek day = DateTime.Now.DayOfWeek;
DayOfWeek start_day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), sr.start_day);
DayOfWeek end_day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), sr.end_day);
if (end_day < start_day)
end_day += 7;
if (day < start_day)
day += 7;
if (day >= start_day && day <= end_day)
{
//Action
}
extention for DateTime
public static bool IsWeekend(this DateTime date)
{
return new[] {DayOfWeek.Sunday, DayOfWeek.Saturday}.Contains(date.DayOfWeek);
}
This is an elegant solution for the problem. It's a class that can easily be imported into other projects. The coding allows the programmer to dynamically assign what days to check for and pass them as a string array to the class. The data can come from a database or be hard coded when you pass it to an instance of this class for processing. It returns the values of True if you're off work and False if you're working that day. Below the class I provided a simple example of implementation. This class features: Dynamic allocation of what days you have off, Simple error handler by setting strings to lowercase before comparing them, Easily integrated with a database that has your work schedule where your days off may not always be the same. Easily integrated as a hard coded number of days off.
// The Class To Check If You're Off Work
class DayOffChecker
{
public bool CheckDays(List<string> DaysOff)
{
string CurrentDay = DateTime.Now.DayOfWeek.ToString();
CurrentDay.ToLower();
foreach (string DayCheck in DaysOff)
{
DayCheck.ToLower();
if (CurrentDay == DayCheck)
{
return (true);
}
}
return (false);
}
}
// Example usage code:
class Program
{
List<string> DaysOff = List<string>();
DaysOff.Add("Saturday"); // Add some values to our list.
DaysOff.Add("Sunday");
DayOffChecker CheckToday = new DayOffChecker();
if(CheckToday.CheckDays(DaysOff))
{
Console.WriteLine("You're Off Today!!!");
}
}
We can also follow similar approach of checking if a given hour is between two hours. Following is the algorithm
checkIfFallsInRange(index,start,end)
bool normalPattern = start <= end ;
if ( normalPattern)
return index>=start && index<=end;
else
return index>=start || index <=end;
My simple solution to determining if the current day is a workday or not is:
public static bool IsWorkDay(this DateTime dt)
{
return IsWorkDay(dt, DayOfWeek.Sunday, DayOfWeek.Saturday);
}
public static bool IsWorkDay(this DateTime dt, params DayOfWeek[] noneWorkDays)
{
return !noneWorkDays.Contains(dt.DayOfWeek);
}
It assumes Sunday / Saturday are non-work days. Otherwise the user can specify the non-work days. And is an extension for easy of use.
Note: To avoid a loop could created a bit flag.
DayOfWeek Day = DateTime.Today.DayOfWeek;
int Time = DateTime.Now.Hour;
if (Day != DayOfWeek.Saturday && Day != DayOfWeek.Sunday)
{
if (Time >= 8 && Time <= 16)
{
//It is Weekdays work hours from 8 AM to 4 PM
{
}
else
{
// It is Weekend
}
You can use the DayOfWeek enumeration in order to see if a date is Sunday or Saturday. http://msdn.microsoft.com/en-us/library/system.dayofweek.aspx I hope this can help.
The line below will return "Sunday"
string nameOfTheDay = DateTime.Now.ToString("dddd", new System.Globalization.CultureInfo("en-GB")).ToLower();
if(nameOfTheDay != "sunday" && nameOfTheDay != "saturday")
{
//Do Stuff
}
public bool IsWeekend(DateTime dateToCheck)
{
DayOfWeek day = (DayOfWeek) dateToCheck.Day;
return ((day == DayOfWeek.Saturday) || (day == DayOfWeek.Sunday));
}
I need to be able to get the difference from the current date with the date from my database. If the difference is 30, I need to display a expiry date message. My code block looks as such:
var expiryDate = DateTime.Now - DateTime.Parse(user[3]);
The thing is, this returns some weird numbers which I can't seem to manage. How would I go about getting just the number of days and then check if it is 30?
Thanks for having a look guys!
DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Parse(user[3]);
TimeSpan ts = dt1 - dt2;
int days = ts.Days;
if (days == 30){
//do something
}
(DateTime.Now - DateTime.Parse(user[3])).TotalDays //this will give you the days.
var timespan = DateTime.Now - DateTime.Parse(user[3]);
var days = timespan.Days;
System.TimeSpan diffResult = dt1 - dt2;
if(diffResult < 0)
{
//your code
}
When you subtract two DateTime instances you get a Timespan.
Validate your value against the TotalDays property of this timespan
var expiryDate = DateTime.Now - DateTime.Parse(user[3]);
expiryDate.TotalDays > 30 // check in this fashion
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How to get the last day of a month?
So far, I have this:
DateTime createDate = new DateTime(year, month, 1).AddMonths(1).AddDays(-1);
Is there a better way?
How about using DaysInMonth:
DateTime createDate = new DateTime (year, month,
DateTime.DaysInMonth(year, month));
(Note to self - must make this easy in Noda Time...)
You can use the method DateTime.DaysInMonth(year,month) to get the number of days in any given month.
Here's an elegant approach I found in a useful DateTime extension library on CodePlex:
http://datetimeextensions.codeplex.com/
Here's some sample code:
public static DateTime First(this DateTime current)
{
DateTime first = current.AddDays(1 - current.Day);
return first;
}
public static DateTime First(this DateTime current, DayOfWeek dayOfWeek)
{
DateTime first = current.First();
if (first.DayOfWeek != dayOfWeek)
{
first = first.Next(dayOfWeek);
}
return first;
}
public static DateTime Last(this DateTime current)
{
int daysInMonth = DateTime.DaysInMonth(current.Year, current.Month);
DateTime last = current.First().AddDays(daysInMonth - 1);
return last;
}
It has a few other useful extensions as well that may be helpful to you.
if you're interested in a custom code version:
var anyDt = DateTime.Now;
var lastDayOfMonth = anyDt.AddMonths(1).AddDays(anyDt.AddMonths(1).Day).Date;
or:
var anyDt = DateTime.Now;
var lastDayOfMonth = anyDt.AddDays(1-anyDt.Day).AddMonths(1).AddDays(-1).Date;
or as a method:
DateTime LastDayInMonth(DateTime anyDt)
{ return anyDt.AddMonths(1).AddDays(anyDt.AddMonths(1).Day).Date; }
or as an extension method:
DateTime LastDayInMonth(DateTime this anyDt)
{ return anyDt.AddMonths(1).AddDays(anyDt.AddMonths(1).Day).Date; }
This question already has answers here:
How do I loop through a date range?
(17 answers)
Closed 6 years ago.
I have a DateTime StartDate and EndDate.
How can I, irrespective of times, iterate across each Day between those two?
Example: StartDate is 7/20/2010 5:10:32 PM and EndDate is 7/29/2010
1:59:12 AM.
I want to be able to iterate across 7/20, 7/21, 7/22 .. 7/29.
for(DateTime date = StartDate; date.Date <= EndDate.Date; date = date.AddDays(1))
{
...
}
The .Date is to make sure you have that last day, like in the example.
An alternative method that might be more reusable is to write an extension method on DateTime and return an IEnumerable.
For example, you can define a class:
public static class MyExtensions
{
public static IEnumerable EachDay(this DateTime start, DateTime end)
{
// Remove time info from start date (we only care about day).
DateTime currentDay = new DateTime(start.Year, start.Month, start.Day);
while (currentDay <= end)
{
yield return currentDay;
currentDay = currentDay.AddDays(1);
}
}
}
Now in the calling code you can do the following:
DateTime start = DateTime.Now;
DateTime end = start.AddDays(20);
foreach (var day in start.EachDay(end))
{
...
}
Another advantage to this approach is that it makes it trivial to add EachWeek, EachMonth etc. These will then all be accessible on DateTime.
You have to be careful about end-date. For example, in
Example: StartDate is 7/20/2010 5:10:32 PM and EndDate is 7/29/2010 1:59:12 AM.
I want to be able to iterate across 7/20, 7/21, 7/22 .. 7/29.
date < endDate will not include 7/29 ever. When you add 1 day to 7/28 5:10 PM - it becomes 7/29 5:10 PM which is higher than 7/29 2 AM.
If that is not what you want then I'd say you do
for (DateTime date = start.Date; date <= end.Date; date += TimeSpan.FromDays(1))
{
Console.WriteLine(date.ToString());
}
or something to that effect.
The loops of #Yuriy Faktorovich, #healsjnr and #mho will all throw a System.ArgumentOutOfRangeException: The added or subtracted value results in an un-representable DateTime
exception if EndDate == DateTime.MaxValue.
To prevent this, add an extra check at the end of the loop
for(DateTime date = StartDate; date.Date <= EndDate.Date; date = date.AddDays(1))
{
...
if (date.Date == DateTime.MaxValue.Date)
{
break;
}
}
(I would have posted this as a comment to #Yuriy Faktorovich's answer, but I lack reputation)
DateTime date = DateTime.Now;
DateTime endDate = date.AddDays(10);
while (date < endDate)
{
Console.WriteLine(date);
date = date.AddDays(1);
}
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).