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

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);

Related

Converting an integer to datetime and comparing the date in 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!

Get all the dates of current week

Say I consider Sunday - Saturday as a week, how do I get all the dates of the current week in c#?
For example, current date is 30th March 2017, the output I need is,
26-March-2017,
27-March-2017,
28-March-2017,
29-March-2017,
30-March-2017,
31-March-2017,
01-April-2017
You can try DateTimeFormat to find out current week's starting date and Linq to generate the string:
DateTime startOfWeek = DateTime.Today.AddDays(
(int) CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek -
(int) DateTime.Today.DayOfWeek);
string result = string.Join("," + Environment.NewLine, Enumerable
.Range(0, 7)
.Select(i => startOfWeek
.AddDays(i)
.ToString("dd-MMMM-yyyy")));
In case of en-US culture you'll get (week starts from Sunday)
26-March-2017, // <- starts from Sunday
27-March-2017,
28-March-2017,
29-March-2017,
30-March-2017,
31-March-2017,
01-April-2017
In case of, say, ru-RU culture you'll get (week starts from Monday)
27-марта-2017, // <- Starts from Monday
28-марта-2017,
29-марта-2017,
30-марта-2017,
31-марта-2017,
01-апреля-2017,
02-апреля-2017
Assuming that Sunday will be the start day of the week, as it is mentioned in the question I suggest following solution.
var today = DateTime.Now.Date; // This can be any date.
Console.WriteLine(today.DayOfWeek);
var day = (int)today.DayOfWeek; //Number of the day in week. (0 - Sunday, 1 - Monday... and so On)
Console.WriteLine(day);
const int totalDaysOfWeek = 7; // Number of days in a week stays constant.
for (var i = -day; i < -day + totalDaysOfWeek; i++)
{
Console.WriteLine(today.AddDays(i).Date);
}
I found this here
DayOfWeek Day = DateTime.Now.DayOfWeek;
int Days = Day - DayOfWeek.Monday; //here you can set your Week Start Day
DateTime WeekStartDate = DateTime.Now.AddDays(-Days);
DateTime WeekEndDate1 = WeekStartDate.AddDays(1);
DateTime WeekEndDate2 = WeekStartDate.AddDays(2);
DateTime WeekEndDate3 = WeekStartDate.AddDays(3);
DateTime WeekEndDate4 = WeekStartDate.AddDays(4);
DateTime WeekEndDate5 = WeekStartDate.AddDays(5);
DateTime WeekEndDate6 = WeekStartDate.AddDays(6);
In my opinion, an extension method is the most useful approach:
public static IEnumerable<DateTime> GetDatesOfWeek(this DateTime date, CultureInfo ci) {
Int32 firstDayOfWeek = (Int32) ci.DateTimeFormat.FirstDayOfWeek;
Int32 dayOfWeek = (Int32) date.DayOfWeek;
DateTime startOfWeek = date.AddDays(firstDayOfWeek - dayOfWeek);
var valuesDaysOfWeek = Enum.GetValues(typeof(DayOfWeek)).Cast<Int32>();
return valuesDaysOfWeek.Select(v => startOfWeek.AddDays(v));
}
Use as follows:
DateTime myDate = DateTime.Today;
IEnumerable<DateTime> result = myDate.GetDatesOfWeek(CultureInfo.CurrentCulture);
foreach ( DateTime d in result ) {
Console.WriteLine(d);
}

Get the number of days between two different DateTime objects

How can I get the difference of days between two DateTime objects?
private static string DaysAfterAYear(DateTime initialDate)
{
DateTime endDate = initialDate.AddYears(1);
endDate = endDate.AddMonths(1);
return ??
}
I need to get the difference between initialDate and endDate.
Use the subtract method:
static void Main(string[] args)
{
DateTime begin = DateTime.Now;
DateTime end = begin.AddYears(1).AddMonths(1);
var result = end.Subtract(begin).TotalDays;
}
DateTime dt1 = new DateTime(2011,01,01);
DateTime dt2 = new DateTime(2011,01,20);
int ireturn = (int)dt2.Subtract(dt1).TotalDays;
Subtracting DateTimes will yield a TimeSpan:
var elapsedDays = (endDate - initialDate).TotalDays;
DateTime start = DateTime.Now;
DateTime end = DateTime.Now.AddDays(5);
TimeSpan span = end.Subtract(start);
return span.Days;
int days = 10;
DateTime initialDate = DateTime.Now;
DateTime endDate = DateTime.Now.AddDays(days);
TimeSpan duration = endDate.Subtract(initialDate);
In this example you can use either span.Days or span.TotalDays, however you have to be very careful with TimeSpan properties. If you look at the TotalHours vs Hours for example you'll see that they are not the same.
The Hours property is the number of hours remaining after the days property has been taken off (in this case zero), the Total hours is the TimeSpan represented in hours.

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));

Exact time between 2 DateTime?

I would like to know many minutes between 2 dates?
Example : Now - tommorow at the exact time would return me 1440.
DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Now.AddDays(1);
int diff = dt2.Subtract(dt1).TotalMinutes;
Look at the TimeSpan class.
DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.Now.AddDays(1);
TimeSpan diff = date2.Subtract(date1);
Console.WriteLine(diff.Minutes);
DateTime currentTime = DateTime.Now;
DateTime tommorowTime = currentTime.AddDays(1);
TimeSpan diffTime = tommorowTime - currentTime ;
Console.WriteLine(diffTime.TotalMinutes);

Categories

Resources