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; }
Related
In my app I have a DateTime and a list of System.DayOfWeek and I need to get the next date.
For example, for the date 2021-06-16 (Wednesday) & a list containing only DayOfWeek.Monday, the next date should be 2021-06-21
Can anyone help here? I think I need to adapt this answer to take a sequence of DayOfWeek with the following signature
public static DateTime GetNextWeekday(DateTime start, IEnumerable<DayOfWeek> days)
Assuming you've got a GetNextWeekday(DateTime, DayOfWeek) method, you can just use LINQ to apply that to all of your specified days, and find the minimum value:
public static DateTime GetNextWeekday(DateTime start, IEnumerable<DayOfWeek> days) =>
days.Select(day => GetNextWeekday(start, day)).Min();
That will fail if days is empty, but that's entirely reasonable.
If you want to accept the current date if it falls on the given day of the week:
public static DateTime GetNextWeekday(DateTime start, IEnumerable<DayOfWeek> days)
{
while (days.Contains(start.DayOfWeek) is false)
{
start = start.AddDays(1);
}
return start;
}
Or if you do not
public static DateTime GetNextWeekday(DateTime start, IEnumerable<DayOfWeek> days)
{
do start = start.AddDays(1);
while (days.Contains(start.DayOfWeek) is false);
return start;
}
How do I convert two integers for instance 28 and 03 into a date like "28.03".
The integers should be input from the user and then converted to the date.
Also, how do I add days to the date?
Just an implementation for your example:
public static string GetDateString(int month, int day)
{
return new DateTime(DateTime.Now.Year, month, day).ToString("dd.MM");
}
To add days to a date you can use the DateTime.AddDays() method:
DateTime date = DateTime.Now;
DateTime otherDate = date.AddDays(7);
The links mentioned by #Giorgi and #D. Petrov are also very useful.
UPDATE:
Here is an example based on your comment.
class ConsoleApp
{
public void Main(string[] args)
{
int day = int.Parse(Console.ReadLine());
int month = int.Parse(Console.ReadLine());
string formattedDate = GetDateString(month, day);
Console.WriteLine(formattedDate);
// You cannot initialize a DateTime struct only with month and day.
// Because Year is not relevant we use the current year.
DateTime date = new DateTime(DateTime.Now.Year, month, day);
DateTime otherDate = date.AddDays(5);
Console.WriteLine(GetFormattedDate(otherDate));
}
public static string GetFormattedDate(DateTime date)
{
// The ToString() method accepts any custom date format string.
// Here is how you can create a custom date format string:
// https://msdn.microsoft.com/en-us/library/8kb3ddd4%28v=vs.110%29.aspx
// dd: days in two digits
// MM: months in two digits
return date.ToString("dd.MM");
}
public static string GetDateString(int month, int day)
{
// Here we construct a DateTime struct
DateTime date = new DateTime(DateTime.Now.Year, month, day);
// Now we extract only the day and month parts.
return GetFormattedDate(date);
}
}
Well if 28 is day and 03 month - you can pass these parameters to the constructor of DateTime structure object. Once you initialize a DateTime object there are various ways to convert it as string. It also has AddDays method.
There is plenty of documentation about what you need (in particular - the DateTime structure). The most relevant information about your current need and the different ways to format yor string with the date you can find here: https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
But as I mentioned before, there is plenty of information in the web.
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);
}
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).