Converting an integer to datetime and comparing the date in c# - c#

I am having an issue in parsing two integers to datetime in C#. I have two integers as follows:
int day = 25;
int month = 08;
var currentYear = DateTime.Now.Year;
var scheduledDate = "25/08/2018";
What I want is to convert day, month and the current year to format dd/MM/yyyy and compare this date to scheduledDate which is in the format of dd/MM/yyyy. Can someone please help me with this ?

Rather than converting DateTime object to String you should always convert String to DateTime object and then compare it.
int day = 25;
int month = 08;
var currentYear = DateTime.Now.Year;
var scheduledDate = "25/08/2018";
var dtScheduledDate = DateTime.ParseExact(scheduledDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
var dtCurrentDate = new DateTime(currentYear, month, day);
if (dtScheduledDate < dtCurrentDate)
{
// ...
}

var yourDateTime = new DateTime(currentYear, month, day);
var yourDateString = yourDateTime.ToString("dd/MM/yyyy");
// compare

If you want to compare only date then you can use Date Property of DateTime
int day = 25;
int month = 08;
var currentYear = DateTime.Now.Year;
var dateToCompare = new DateTime(currentYear, month, day);
var scheduledDt = "25/08/2018";
var scheduledDate = DateTime.ParseExact(scheduledDt, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
if(dateToCompare.Date == scheduledDate.Date)
{
//Your logic
}
POC: .Net Fiddler

Try the following, you could use DateTime.ToString() method to convert it into the format you need.
int day = 25;
int month = 08;
var currentYear = DateTime.Now.Year;
var date = new DateTime(DateTime.Now.Year, month, day);
var formattedDate = date.ToString("dd/MM/yyyy");
var scheduledDate = "25/08/2018";
// Compare formattedDate and scheduledDate
OR
You could consider converting the scheduledDate string to date time and compare the date time objects, if that's more appropriate:
var scheduledDate = "25/08/2018";
var parsedDate = DateTime.ParseExact(scheduledDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
var date = new DateTime(DateTime.Now.Year, month, day);
// compare date & parsed date
bool areEqual = date.Equals(parsedDate);

If I understand your question, just keep the proceeding zero,
int day = 25;
int month = 08;
var currentYear = DateTime.Now.Year;
var targetDate = $"{day}/{month.ToString().PadLeft(2,'0')}/{currentYear}";
var scheduledDate = "25/08/2018";
var difference = DateTime.Compare(DateTime.Parse(targetDate),
DateTime.Parse(scheduledDate));

In case you just want to convert it to a string, this should be the easiest way:
int day = 25;
int month = 08;
var currentYear = DateTime.Now.Year;
// {day:D2} is equivalent to day.ToString("D2") which pads integers to a length of two
var createdDate = $"{day:D2}/{month:D2}/{currentYear}";
var scheduledDate = "25/08/2018";
EDIT
Picking up on a few things people here said, parsing both to a DateTime might be more suitable for the comparing part:
DateTime createdDateTime = new DateTime(currentYear, month, day);
DateTime scheduledDateTime = DateTime.ParseExact(scheduledDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
// Compare if it's the same day
if (createdDateTime.Date == scheduledDateTime.Date)
{
// do stuff
}
// Get the difference in Days
int dayDifference = (createdDateTime - scheduledDateTime).Days;
Alternatively .TotalDays instead of .Days returns a double

int day = 25;
int month = 08;
var currentYear = DateTime.Now.Year;
var scheduledDate = "25/08/2018";
// parse string into DateTime structure
var ci = new CultureInfo("en-UK");
var dtScheduledDate = DateTime.Parse(scheduledDate, ci);
var dtOther = new DateTime(currentYear, month, day);
if(dtOther > dtScheduledDate)
{
...
}

In this case if your variable scheduleDate is a string you can convert the other variables (day,month and currentYear) into a string in the format you want:
var dt = day + "/" + month + "/" + currentYear;
So to compare you do this:
if(dt.Equals(scheduleDate))
//Do some
else
//other thing

static void Main(string[] args)
{
int transactionDate = 20201010;
int? transactionTime = 210000;
var agreementDate = DateTime.Today;
var previousDate = agreementDate.AddDays(-1);
var agreementHour = 22;
var agreementMinute = 0;
var agreementSecond = 0;
var startDate = new DateTime(previousDate.Year, previousDate.Month, previousDate.Day, agreementHour, agreementMinute, agreementSecond);
var endDate = new DateTime(agreementDate.Year, agreementDate.Month, agreementDate.Day, agreementHour, agreementMinute, agreementSecond);
DateTime selectedDate = Convert.ToDateTime(transactionDate.ToString().Substring(6, 2) + "/" + transactionDate.ToString().Substring(4, 2) + "/" + transactionDate.ToString().Substring(0, 4) + " " + string.Format("{0:00:00:00}", transactionTime));
Console.WriteLine("Selected Date : " + selectedDate.ToString());
Console.WriteLine("Start Date : " + startDate.ToString());
Console.WriteLine("End Date : " + endDate.ToString());
if (selectedDate > startDate && selectedDate <= endDate)
Console.WriteLine("Between two dates..");
else if (selectedDate <= startDate)
Console.WriteLine("Less than or equal to the start date!");
else if (selectedDate > endDate)
Console.WriteLine("Greater than end date!");
else
Console.WriteLine("Out of date ranges!");
}
Output:
Selected Date : 10.10.2020 21:00:00
Start Date : 8.10.2020 22:00:00
End Date : 9.10.2020 22:00:00
Greater than end date!

Related

How to get the list of week start date (Monday) and end date (Sunday) for the year in C#

I want to get only weeks for the whole year where I want to get the start date (Monday) and end date (Friday) in C#.
For example: 1/52 = 02 Jan (Monday) - 09 Jan (Sunday) 2/52 = 10 Jan (Monday) - 17 Jan (Sunday)
and so on.
I can get current week dates but no idea how to get for the year.
// We Set the Monday as the first day of the week.
DayOfWeek day = datetime.DayOfWeek;
int days = day - DayOfWeek.Monday;
if (days == -1)
{
days = 6; // this is when we have sunday as a DayOfWeek day
}
DateTime start = datetime.AddDays(-days);
DateTime end = start.AddDays(6);
Without making it complicated you can simply use while like below.
while (datetime.DayOfWeek != DayOfWeek.Monday)
{
datetime= datetime.AddDays(1);
}
DateTime start = datetime;
DateTime end = start.AddDays(6);
Or you want to find week from the week index 1/52 for any year then write function like below. Use it like GetWeek(1, 2020) to get 06.01.2020 - 12.01.2020. Format it as per your requirement.
public DateTime GetNextMonday(DateTime datetime)
{
return datetime.AddDays((7 - (int)datetime.DayOfWeek + (int)DayOfWeek.Monday) % 7);
}
public string GetWeek(int week, int year)
{
var start = GetNextMonday(new DateTime(year, 1, 1).AddDays((week-1)*7));
var end = start.AddDays(6);
return start.ToShortDateString() + " - " + end.ToShortDateString();
}
As far as I have understood, probably this will help, I tried the below and it displayed for me the start and end dates for the specified years:
DateTime starting = new DateTime(2020, 1, 1);
DateTime ending = new DateTime(2020, 12, 1);
DateTime currentDay = starting;
DateTime start = currentDay;
DateTime end = currentDay;
while (ending.Year >= currentDay.Year)
{
if (currentDay.DayOfWeek == DayOfWeek.Monday)
{
start = currentDay;
end = start.AddDays(6);
currentDay = end;
Console.WriteLine(start + "(" + start.DayOfWeek + ")");
Console.WriteLine(end + "(" + end.DayOfWeek + ")");
}
else
{
currentDay = currentDay.AddDays(1);
}
}
You can use methods below to calculate start day of any week of any year
public static DateTime StartOfNthWeekOfYear(int year, int weekNumber, DayOfWeek firstDayOfWeek)
{
if(weekNumber < 1)
{
throw new ArgumentOutOfRangeException(nameof(weekNumber));
}
DateTime startOfWeek = StartOfFirstWeekOfYear(year, firstDayOfWeek).AddDays((weekNumber - 1) * 7);
DateTime endOfWeek = startOfWeek.AddDays(6);
if(endOfWeek.Year != year || startOfWeek.Year != year)
{
throw new ArgumentOutOfRangeException(nameof(weekNumber));
}
return startOfWeek;
}
public static DateTime StartOfFirstWeekOfYear(int year, DayOfWeek firstDayOfWeek)
{
DateTime startOfYear = new DateTime(year, 1, 1);
if (startOfYear.DayOfWeek != firstDayOfWeek)
{
return StartOfWeek(startOfYear, firstDayOfWeek).AddDays(7);
}
return startOfYear;
}
public static DateTime StartOfWeek(DateTime value, DayOfWeek firstDayOfWeek)
{
if (value.DayOfWeek != firstDayOfWeek)
{
return value.AddDays(-((7 + (int)value.DayOfWeek - (int)firstDayOfWeek) % 7));
}
return value;
}
I think this should work for Gregorian calendars and takes into account different cultures:
public static IList<DateTime> GetFirstDayOfWeekDates(CultureInfo cultureInfo, int year)
{
var lastDateOfYear = new DateTime(year, 12, 31);
var firstDate = new DateTime(year, 1, 1);
var dayOfWeek = cultureInfo.DateTimeFormat.FirstDayOfWeek;
while (firstDate.DayOfWeek != dayOfWeek)
{
firstDate = firstDate.AddDays(1);
}
var numberOfWeeksInYear = cultureInfo.Calendar.GetWeekOfYear(lastDateOfYear, cultureInfo.DateTimeFormat.CalendarWeekRule, dayOfWeek);
var firstDayOfWeekDates = new List<DateTime>();
firstDayOfWeekDates.Add(firstDate);
var currentDate = firstDate;
for (int i = 0; i < numberOfWeeksInYear; i++)
{
var weekLater = currentDate.AddDays(7);
if (weekLater.Year == year)
{
currentDate = weekLater;
firstDayOfWeekDates.Add(currentDate);
}
}
return firstDayOfWeekDates;
}
You can test this with a console app like this (make the method static):
static void Main(string[] args)
{
var ci = new CultureInfo("en-GB");
var dates = GetFirstDayOfWeekDates(ci, DateTime.Now.Year);
foreach (var dt in dates)
{
Console.WriteLine("Date: " + dt.ToShortDateString());
}
Console.ReadLine();
}
It brings back the following:
If you want to include the end date of the week as well then you can tweak this slightly by adding a new class called WeekDate:
public class WeekDate
{
public DateTime StartOfWeek { get; set; }
public DateTime EndOfWeek { get; set; }
}
GetFirstDayOfWeekDates then becomes:
public static IList<WeekDate> GetFirstDayOfWeekDates(CultureInfo cultureInfo, int year)
{
var lastDateOfYear = new DateTime(year, 12, 31);
var firstDate = new DateTime(year, 1, 1);
var dayOfWeek = cultureInfo.DateTimeFormat.FirstDayOfWeek;
while (firstDate.DayOfWeek != dayOfWeek)
{
firstDate = firstDate.AddDays(1);
}
var numberOfWeeksInYear = cultureInfo.Calendar.GetWeekOfYear(lastDateOfYear, cultureInfo.DateTimeFormat.CalendarWeekRule, dayOfWeek);
var firstDayOfWeekDates = new List<WeekDate>();
firstDayOfWeekDates.Add(new WeekDate { StartOfWeek = firstDate, EndOfWeek = firstDate.AddDays(6) });
var currentDate = firstDate;
for (int i = 0; i < numberOfWeeksInYear; i++)
{
var weekLater = currentDate.AddDays(7);
if (weekLater.Year == year)
{
currentDate = currentDate.AddDays(7);
firstDayOfWeekDates.Add(new WeekDate { StartOfWeek = currentDate, EndOfWeek = currentDate.AddDays(6) });
}
}
return firstDayOfWeekDates;
}
Which returns:

Get Monday's date every week in between two dates

How to get a Monday dates after every week in between from given start date and end date
For example
Start date : 28-12-2018
End date : 29-12-2019
So the following dates should be in the list
Monday : 3-12-2018
Monday : 14-01-2019
Monday : 28-01-2019
Monday : 11-02-2019
This my code: I am unable to find the every week in between from the range.how to identify dates that its from 1 week.
Any help will be appropriated
DateTime startDate = LimitVmodel.StartDate;
DateTime endDate = LimitVmodel.EndDate;
TimeSpan diff = endDate - startDate;
int days = diff.Days;
for (long i = 0; i <= days; i++)
// for (DateTime date = TIR.NetCore.PersianDateTime.ConvertShToM(LimitVmodel.StartDate); date <= TIR.NetCore.PersianDateTime.ConvertShToM(LimitVmodel.EndDate); date = date.AddDays((Double)Week))
{
DateTime date;
date = startDate.AddDays(i);
DateYear a = new DateYear();
switch (LimitVmodel.Day)
{
case "Saturday":
if (date.DayOfWeek == DayOfWeek.Saturday)
{
allDates.Add(a);
}
break;
case "Sunday":
if (date.DayOfWeek == DayOfWeek.Sunday)
{
allDates.Add(a);
}
break;
case "Monday":
if (date.DayOfWeek == DayOfWeek.Monday)
{
allDates.Add(a);
}
break;
}
Here is a solution with Extension.
Gets a DateTime range and a day of week.
Returns a list of DateTime.
public static class DateUtils
{
public static List<DateTime> GetWeekdayInRange(this DateTime from, DateTime to, DayOfWeek day)
{
const int daysInWeek = 7;
var result = new List<DateTime>();
var daysToAdd = ((int)day - (int)from.DayOfWeek + daysInWeek) % daysInWeek;
do
{
from = from.AddDays(daysToAdd);
result.Add(from);
daysToAdd = daysInWeek;
} while (from < to);
return result;
}
}
Usage:
namespace DatesTest
{
class Program
{
static void Main(string[] args)
{
var from = DateTime.Today; // 25/8/2019
var to = DateTime.Today.AddDays(23); // 23/9/2019
var allMondays = from.GetWeekdayInRange(to, DayOfWeek.Monday);
}
}
}
Output:
{8/26/2019 12:00:00 AM}
{9/2/2019 12:00:00 AM}
{9/9/2019 12:00:00 AM}
{9/16/2019 12:00:00 AM}
{9/23/2019 12:00:00 AM}
DateTime date = LimitVmodel.StartDate;
switch (LimitVmodel) {
case "Monday":
while (date.DayOfWeek != DayOfWeek.Monday) {
date = date.AddDays(1);
}
break;
case "Tuesday":
while (date.DayOfWeek != DayOfWeek.Tuesday) {
date = date.AddDays(1);
}
break;
//Etc...
}
AllDates.add(date);
while (DateTime.compare(date, LimitVmodel.EndDate) <= 0) {
date = date.AddDays(7);
AllDates.add(date);
}
You can use the for loop to check for the day which you are getting in LimitVmodel.Day and collate all the dates which fall on that day. Something like this:
DateTime startDate = LimitVmodel.StartDate;
DateTime endDate = LimitVmodel.EndDate;
int days = (endDate - startDate).Days;
string myDay = LimitVmodel.Day;
var myDayDayOfWeek = (DayOfWeek)Enum.Parse(typeof(DayOfWeek),myDay); //convert string to DayOfWeek type
var allDates = new List<DateTime>();
for(int i=0; i < days; i++)
{
var currDate = startDate.AddDays(i);
if(currDate.DayOfWeek == myDayDayOfWeek)
allDates.Add(currDate);
}

How do I compute a date a specified period in the future?

I have this:
string dataNow = DateTime.Today.tostring();
string dateAfter = dateNow + ( 20 days);
How do I find the date in 20 days?
How do I find the number of days in the month?
Your likely intent is to work with a date as a date type DateTime. In which case, don't call ToString() before you've completed manipulating the date:
string dataNow = DateTime.Today.AddDays(20).ToString();
DateTime.AddDays
After update:
To get the number of days in the current month:
var date = DateTime.Today;
int days = DateTime.DaysInMonth(date.Year, date.Month);
DateTime.DaysInMonth
This should do it:
DateTime dtNow = DateTime.Today;
string dateNow = dtNow.ToString();
string dateAfter = dtNow.AddDays(20).ToString();
int DaysInTheMonth = DateTime.DaysInMonth(dtNow.Year, dtNow.Month);
DateTime today = DateTime.Today;
DateTime later = today.AddDays(20);
string todayAsString = today.ToString("d");
string laterAsString = later.ToString("d");
int daysThisMonth = DateTime.DaysInMonth(today.Year, today.Month);
int daysLaterMonth = DateTime.DaysInMonth(later.Year, later.Month);

Getting all DateTimes between two 'DateTime's in C#

I have two DateTimes, and I want to get all DateTimes between these Dates. Such as, if my Dates are like 01.01.2010 - 05.01.2010, my function should return me a list of date (List), and it must contain 01.01.2010, 02.01.2010, 03.01.2010, 04.01.2010, and 05.01.2010.
I wrote a function like this. It works fine, if my dates are in a month. It won't work if my dates are like 01.01.2010 - 05.02.2010. Because the month changed, and my function can't handle it. Is there a function in C# that returns all dates between two dates? Or how can I handle month change?
public void GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate)
{
List<DateTime> allDates = new List<DateTime>();
int starting = startingDate.Day;
int ending = endingDate.Day;
for (int i = starting; i <= ending; i++)
{
allDates.Add(new DateTime(startingDate.Year, startingDate.Month, i));
}
Question solved, see Tim Robinson's simple answer to use.
You can use DateTime objects directly in the loop, in place of your int. DateTime.AddDays handles month ends correctly.
for (DateTime date = startingDate; date <= endingDate; date = date.AddDays(1))
allDates.Add(date);
How about something like this?
public IEnumerable<DateTime> DateRange(DateTime fromDate, DateTime toDate)
{
return Enumerable.Range(0, toDate.Subtract(fromDate).Days + 1)
.Select(d => fromDate.AddDays(d));
}
Edit: Tested now. :)
public IEnumerable<DateTime> GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate)
{
if (endingDate < startingDate)
{
throw new ArgumentException("endingDate should be after startingDate");
}
var ts = endingDate - startingDate;
for (int i = 0; i < ts.TotalDays; i++)
{
yield return startingDate.AddDays(i);
}
}
You were so close... just don't use the day, use the whole date.
static IEnumerable<DateTime> GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate)
{
List<DateTime> allDates = new List<DateTime>();
for (DateTime i = startingDate; i <= endingDate; i = i.AddDays(1))
{
allDates.Add(i);
}
return allDates.AsReadOnly();
}
Given a lowerdate value and higher date value in String and a frequency as the third parameter this method should return a dictionary of dates; where the key is the start value of a date range and the value is the respective range.
This works fine if the frequency is either weekly or monthly- you can customize it as per your need.
The date values passed should be in proper format or you might need to format it using tryParseExact or something like that.
protected static Dictionary<DateTime, String> getDateRange(String lowerDate, String higherDate, String frequency)
{
DateTime startDate, endDate;
startDate = Convert.ToDateTime(lowerDate);
endDate = Convert.ToDateTime(higherDate);
Dictionary<DateTime, String> returnDict = new Dictionary<DateTime, String>();
while (frequency.Equals("weekly") ? (startDate.AddDays(7) <= endDate) : (startDate.AddMonths(1) <= endDate))
{
if (frequency.Equals("weekly"))
{
returnDict.Add(startDate, startDate + "-" + startDate.AddDays(7));
startDate = startDate.AddDays(8);
}
if (frequency.Equals("monthly"))
{
returnDict.Add(startDate, startDate + "-" + startDate.AddMonths(1));
startDate = startDate.AddMonths(1).AddDays(1);
}
}
returnDict.Add(startDate, startDate + "-" + endDate);
return returnDict;
}
The top solutions will fail if the date includes different hours. Here is a solution getting all hours and all days:
All Days:
static public List<string> get_days_between_two_dates(DateTime start_date, DateTime end_date)
{
List<string> days_list = new List<string>();
DateTime temp_start;
DateTime temp_end;
//--Normalize dates by getting rid of minues since they will get in the way when doing the loop
temp_start = new DateTime(start_date.Year, start_date.Month, start_date.Day);
temp_end = new DateTime(end_date.Year, end_date.Month, end_date.Day);
//--Example Should return
//--1-12-2014 5:59AM - 1-13-2014 6:01AM return 12 and 13
for (DateTime date = temp_start; date <= temp_end; date = date.AddDays(1))
{
days_list.Add(date.ToShortDateString());
}
return days_list;
}
All Hours:
static public List<string> get_hours_between_two_dates(DateTime start_date, DateTime end_date)
{
List<string> hours_24_list = new List<string>();
DateTime temp_start;
DateTime temp_end;
//--Normalize dates by getting rid of minutes since they will get in the way when doing the loop
temp_start = new DateTime(start_date.Year, start_date.Month, start_date.Day, start_date.Hour, 0, 0);
temp_end = new DateTime(end_date.Year, end_date.Month, end_date.Day, end_date.Hour, 0, 0);
//--Example Should return
//--5:59AM - 6:01AM return 5am and 6am
for (DateTime date = temp_start; date <= temp_end; date = date.AddHours(1))
{
hours_24_list.Add(date.ToShortTimeString());
}
return hours_24_list;
}
Based on your starting code and using the features available at the time of writing, here is a quick console app to demonstrate how to do it - use AddDays() instead:
class Program
{
static void Main(string[] args)
{
GetDates(new DateTime(2010, 1, 1), new DateTime(2010, 2, 5));
Console.ReadKey();
}
static List<DateTime> GetDates(DateTime startDate, DateTime endDate)
{
List<DateTime> dates = new List<DateTime>();
while ((startDate = startDate.AddDays(1)) < endDate)
dates.Add(startDate);
return dates;
}
}
Although I think the Enumerable.Range() answer from Matt is a nicer solution.
static IEnumerable<DateTime> GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate)
{
List<DateTime> allDates = new List<DateTime>();
for (DateTime i = startingDate; i <= endingDate; i = i.AddDays(1))
{
allDates.Add(i);
}
return allDates.AsReadOnly();
}

Get the previous month's first and last day dates in c#

I can't think of an easy one or two liner that would get the previous months first day and last day.
I am LINQ-ifying a survey web app, and they squeezed a new requirement in.
The survey must include all of the service requests for the previous month. So if it is April 15th, I need all of Marches request ids.
var RequestIds = (from r in rdc.request
where r.dteCreated >= LastMonthsFirstDate &&
r.dteCreated <= LastMonthsLastDate
select r.intRequestId);
I just can't think of the dates easily without a switch. Unless I'm blind and overlooking an internal method of doing it.
var today = DateTime.Today;
var month = new DateTime(today.Year, today.Month, 1);
var first = month.AddMonths(-1);
var last = month.AddDays(-1);
In-line them if you really need one or two lines.
The way I've done this in the past is first get the first day of this month
dFirstDayOfThisMonth = DateTime.Today.AddDays( - ( DateTime.Today.Day - 1 ) );
Then subtract a day to get end of last month
dLastDayOfLastMonth = dFirstDayOfThisMonth.AddDays (-1);
Then subtract a month to get first day of previous month
dFirstDayOfLastMonth = dFirstDayOfThisMonth.AddMonths(-1);
using Fluent DateTime https://github.com/FluentDateTime/FluentDateTime
var lastMonth = 1.Months().Ago().Date;
var firstDayOfMonth = lastMonth.FirstDayOfMonth();
var lastDayOfMonth = lastMonth.LastDayOfMonth();
DateTime LastMonthLastDate = DateTime.Today.AddDays(0 - DateTime.Today.Day);
DateTime LastMonthFirstDate = LastMonthLastDate.AddDays(1 - LastMonthLastDate.Day);
I use this simple one-liner:
public static DateTime GetLastDayOfPreviousMonth(this DateTime date)
{
return date.AddDays(-date.Day);
}
Be aware, that it retains the time.
An approach using extension methods:
class Program
{
static void Main(string[] args)
{
DateTime t = DateTime.Now;
DateTime p = t.PreviousMonthFirstDay();
Console.WriteLine( p.ToShortDateString() );
p = t.PreviousMonthLastDay();
Console.WriteLine( p.ToShortDateString() );
Console.ReadKey();
}
}
public static class Helpers
{
public static DateTime PreviousMonthFirstDay( this DateTime currentDate )
{
DateTime d = currentDate.PreviousMonthLastDay();
return new DateTime( d.Year, d.Month, 1 );
}
public static DateTime PreviousMonthLastDay( this DateTime currentDate )
{
return new DateTime( currentDate.Year, currentDate.Month, 1 ).AddDays( -1 );
}
}
See this link
http://www.codeplex.com/fluentdatetime
for some inspired DateTime extensions.
The canonical use case in e-commerce is credit card expiration dates, MM/yy. Subtract one second instead of one day. Otherwise the card will appear expired for the entire last day of the expiration month.
DateTime expiration = DateTime.Parse("07/2013");
DateTime endOfTheMonthExpiration = new DateTime(
expiration.Year, expiration.Month, 1).AddMonths(1).AddSeconds(-1);
If there's any chance that your datetimes aren't strict calendar dates, you should consider using enddate exclusion comparisons...
This will prevent you from missing any requests created during the date of Jan 31.
DateTime now = DateTime.Now;
DateTime thisMonth = new DateTime(now.Year, now.Month, 1);
DateTime lastMonth = thisMonth.AddMonths(-1);
var RequestIds = rdc.request
.Where(r => lastMonth <= r.dteCreated)
.Where(r => r.dteCreated < thisMonth)
.Select(r => r.intRequestId);
DateTime now = DateTime.Now;
int prevMonth = now.AddMonths(-1).Month;
int year = now.AddMonths(-1).Year;
int daysInPrevMonth = DateTime.DaysInMonth(year, prevMonth);
DateTime firstDayPrevMonth = new DateTime(year, prevMonth, 1);
DateTime lastDayPrevMonth = new DateTime(year, prevMonth, daysInPrevMonth);
Console.WriteLine("{0} {1}", firstDayPrevMonth.ToShortDateString(),
lastDayPrevMonth.ToShortDateString());
This is a take on Mike W's answer:
internal static DateTime GetPreviousMonth(bool returnLastDayOfMonth)
{
DateTime firstDayOfThisMonth = DateTime.Today.AddDays( - ( DateTime.Today.Day - 1 ) );
DateTime lastDayOfLastMonth = firstDayOfThisMonth.AddDays (-1);
if (returnLastDayOfMonth) return lastDayOfLastMonth;
return firstDayOfThisMonth.AddMonths(-1);
}
You can call it like so:
dateTimePickerFrom.Value = GetPreviousMonth(false);
dateTimePickerTo.Value = GetPreviousMonth(true);
var lastMonth = DateTime.Today.AddMonths(-1);
dRet1 = new DateTime(lastMonth.Year, lastMonth.Month, 1);
dRet2 = new DateTime(lastMonth.Year, lastMonth.Month, DateTime.DaysInMonth(lastMonth.Year, lastMonth.Month));

Categories

Resources