Calculate Last Day of the Next Month - c#

I am attempting to use the DateTime function in C# to calculate the last day of next month.
For example, today is December 17th 2015. I want the DateTime function to return January 31st 2016 (the last day of next month).
I am using the following to calculate the first day of next month (this works):
DateTime firstDayNextMonth = DateTime.Today.AddDays(-DateTime.Now.Day+1).AddMonths(1);

DateTime reference = DateTime.Now;
DateTime firstDayThisMonth = new DateTime(reference.Year, reference.Month, 1);
DateTime firstDayPlusTwoMonths = firstDayThisMonth.AddMonths(2);
DateTime lastDayNextMonth = firstDayPlusTwoMonths.AddDays(-1);
DateTime endOfLastDayNextMonth = firstDayPlusTwoMonths.AddTicks(-1);
Demo: http://rextester.com/AKDI52378

//system date or any date u want this case it is a calendar picker - 22/03/2016
DateTime today = dtpFrom.Value;
//Add a month to your date example , it now becomes - 22/04/2016
DateTime endOfMonth = new DateTime(today.Year, today.Month,today.Day).AddMonths(1);
//Get the last date off the above which is - 30
int getlastday = DateTime.DaysInMonth(endOfMonth.Year, endOfMonth.Month);
//Now set the date to the value which will be the last day off the next month - 30/04/2016
DateTime newDate = new DateTime(endOfMonth.Year, endOfMonth.Month, getlastday);

DateTime.DaysInMonth(DateTime.Now.AddMonths(1).Year, DateTime.Now.AddMonths(1).Month);

var lastDayInNextMonth = DateTime.DaysInMonth(DateTime.Now.AddMonths(1).Year, DateTime.Now.AddMonths(1).Month );
# Ben : DateTime.Now.AddMonths(1) will add 1 month to the current date not substract 11 months.
DateTime.Now.AddMonths(1).Year will give 2016 not 2015 refer the attached image

try this:
int Day= DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month+1>12 ? 01 : DateTime.Now.Month+1 );

Related

How do I handle datetime with no day in a linq comparison?

I am given two dates as strings like this:
Beginning month: 10
Beginning year: 2010
Ending month: 01
Ending Year 2020
I want to query my entity and get everything that is equal or between these ranges.
So, I want everything from 10/2010 to 01/2020.
I have this code and I got stuck on how to convert the date correctly and the comparison:
dollartotals = (from x in se.AchBatches
where x.CompanyCode == company &&
DbFunctions.TruncateTime(x.DateTimeSubmitted) >=
// stuck here
select x.DollarTotal).Sum();
How do I handle the individual month/year strings and make a date comparison without a day?
Thanks for any assistance!
You want to check against the actual datetime submitted, not a truncated version of it.
The key is to build actual datetimes in advance, then just do a regular date window check.
Assume you have four strings as listed in your question:
//you might use TryConvert or a Try block here to validate your string data...
int beginYear = Integer.Convert(strBeginYear);
int beginMonth = Integer.Convert(strBeginMonth);
int endYear = Integer.Convert(strEndYear);
int endMonth = Integer.Convert(strEndMonth);
DateTime start = new DateTime(beginYear, beginMonth, 1);
DateTime endLimit = new DateTime(endYear, endMonth, 1).AddMonths(1);
dollartotals = (from x in se.AchBatches
where x.CompanyCode == company &&
x.DateTimeSubmitted >= start &&
x.DateTimeSubmitted < endLimit
select x.DollarTotal).Sum();
I want everything from 10/2010 to 01/2020.
Not sure if you want a DateTime sequence with every Tick between those dates, or every second, or every Day. Let's assume you want every Day: All Days from startDate.Date until and inclusive endDate.Date.
I use StartDate.Date, so if StartDate is 2020-02-05 13:20:14, then you still get February 5th 2020 at 00:00:00
IEnumerable<DateTime> GetDateRange(DateTime startDate, DateTime endDate)
{
DateTime lastDate = endDate.Date;
DateTime date = startDate.Date;
while (date <= lastDate)
{
yield return date;
date = date.AddDays(+1);
}
}
Usage:
var allDaysOfFebruary2020 = GetDateRange(new DateTime(2020, 01, 01),
new DateTime(2020, 02, 29));
You'll get the sequence from 1st February 2020 until and inclusive 29th February 2020.

How to create a future date having known the month and year

I have to calculate the date or create a date which is 10 days into next month. I have with me month and year. If the month is April and year is 2019 I need a date which is 10th of may 2019.
You can simply use the methods available in the DateTime structure to do math with dates
// As example, replaces it with whatever date you have
DateTime current = new DateTime(2019,4,5);
DateTime next = new DateTime(current.Year, current.Month, 1).AddMonths(1).AddDays(9);
You can use AddMonths() and AddDays() extension method of DateTime.
From MSDN :
AddMonths() : Returns a new DateTime that adds the specified number of
months to the value of this instance.
AddDays() : Returns a new DateTime that adds the specified number of
days to the value of this instance.
//Considered this is your Current date
DateTime existingDate = new DateTime(2019, 4, 1);
//Below code will add +1 month to current month and +9 days to current date.
var result = existingDate.AddMonths(1).AddDays(9);
Output :
CurrentDate : 4/1/2019 12:00:00 AM
Next Date (+1 month and +9 days) :5/10/2019 12:00:00 AM
POC : .net Fiddle
var dateNow = DateTime.Now.AddMonths(1);
var date = new DateTime(dateNow.Year, dateNow.Month, 10);
Try this:
DateTime dt = new DateTime(2019, 04, 01);
DateTime newDT = dt.AddMonths(1).AddDays(9);

Get week number for different startdate

I can get week number if I use normal way like that. As you know this one calculates week number according to normal start date which is 01.01.2015.
CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(mydate, CultureInfo.CurrentCulture.DateTimeFormat.CalendarWeekRule, CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek)
But I want to change that start date. For instance my first week of year will be 01.07.2015 and according to that date I want to calculate week of year for given date.
Substract a difference between new year and your start date from the mydate object
var startDate = new DateTime(2015, 7, 1);
var newYear = new DateTime(2015, 1, 1);
var culture = CultureInfo.CurrentCulture;
var weekOfYear = culture.Calendar.GetWeekOfYear(
mydate.Add(newYear - startDate),
culture.DateTimeFormat.CalendarWeekRule,
culture.DateTimeFormat.FirstDayOfWeek);
Maybe you could calculate the week number for your start date (e.g 01.07.2015 - 27) and then what is the week number for the actual date - e.g 12.12.2015 (50), and then just subtract - in this case 23?
Just subtract the number of days between your wished week-1 date and the default start date and use that offset each time you calculate (.AddDays(offset)).
That way :
DateTime startDateTime = new DateTime(2015,07,01) ;
int fisrtDayOfWeek = 0 ; // 0:sunday for US, 1:Monday for many other coutries
DateTime week1StartDateTime = startDateTime ;
for (int i=1;i<6;i++) if ((int)startDateTime.AddDays(i).Day==fisrtDayOfWeek )
week1StartDateTime = startDateTime.AddDays(i) ;
int weekNumber= mydate<week1StartDateTime ? 1 :
((int)(mydate-week1StartDateTime).TotalDays)/7+1 ;
// note : casting double to int provides the floor (not round)

Setting A particular Day in a date

I am using Calender Extender Control in the AjaxControlToolkit. There are basically 2 controls of date : Start Date and End date (both associated with calender extender). Based on start Date selected, I populate date in the end date field like adding no of months or days. But like I have been able to add months, but also wants to set a particular day of that month which I am unable to do.
Example:
Today date is 18 Dec 2012. Something like 1st of every three months, So I add 3 months the month comes out to be Feb 2013. But I want to set Day 1st Feb 2013. I am unable to do it. Kindly help.
You can set whatever day of month by add month.
DateTime todayDate = DateTime.Now;
DateTime after3MonthDate = todayDate.AddMonths(3);
//Set First Day of Month
after3MonthDate = new DateTime(after3MonthDate.Year, after3MonthDate.Month, 1);
This code can be used for existing date time variable to set the day part to the first day of the month:
if(myDate.Day > 1)
{
myDate = myDate.AddDays(-(myDate.Day - 1));
}
Try this:
// Here is the simple wrapper method to get the first day of the month:
public DateTime FirstDayOfMonthFromDateTime(DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, 1);
}
// Set the due date...
DueDate.Text = (FirstDayOfMonthFromDateTime(DateTime.Parse(StartDate.Text).AddMonths(N))).ToShortDateString();
You can also modify the wrapper method to get any day of the month:
public DateTime DayOfMonthFromDateTime(DateTime dateTime, int day)
{
return new DateTime(dateTime.Year, dateTime.Month, day);
}

How do you convert an int representing days-from-zero to DateTime?

I have an int representing a number of Gregorian days from Year Zero (thanks, Erlang). How do I convert this to a DateTime object? I can't create a DateTime(0,0,0), and Convert.DateTime(int) throws an invalid cast.
If you have a number, and you know the date that it represents (from Erlang), you can calculate the offset from any date you choose. Preferred is a base date in the zone that the results will be in, this will minimize calender conversion effects. (The Gregorian calendar is valid from about 1600).
If you know that offset, you can use the choosen date as the base for future calculations.
Example:
I want my offset date to be: 1/1/2000. This will be the date that I calculcate from.
I know number 37892 from erlang is actually 1/1/1970 (this is an example).
Then I can calculate the offset:
var myBaseDate = new DateTime(2000,1,1);
var exampleNrOfDays = 37892;
var exampleDate = new DateTime(1970,1,1);
var offset = exampleDate - myBaseDate;
var offsetInDays = exampleNrOfDays - (int)offset.TotalDays;
// Now I can calculate
var daysFromErlang = 30000; // <= example
var theDate = myBaseDate.AddDays(daysFromErlang - offsetInDays);
This shows how to calculate number of days from a given date. http://dotnetperls.com/datetime-elapsed
if day zero is 0/0/0 then it is 365+30+1 day before DateTime.Min which is 1/1/1. So you can subtract days from year zero by 365+30+1 and add to DateTime.Min
Now Month 1 is January which is 31 days but what is Month 0? I assumed it is 30 days.
With 0, you probably mean 0:00 on the 1st of January, year 1. There is no year 0 in the gregorian calendar as far as i know.
If the above is right, you can just do
DateTime date = new DateTime();
date.AddDays(numberOfDays);
because the default constructor 'DateTime()' returns the "zero" DateTime object.
See the DateTime reference for more informations.
I am not sure if you are aware of this, but there is a Calendar object in System.Globalization. Not only that but there is a GregorianCalendar object as well.
so try this:
GregorianCalendar calendar = new GregorianCalendar();
DateTime minSupportedDateTime = calendar.MinSupportedDateTime;
//which is the first moment of January 1, 0001 C.E.
DateTime myDate = minSupportedDateTime.AddDays(55000);
//this is when you add the number of days you have.
Thanks,
Bleepzter
PS. Don't forget to mark my answer if it has helped you solve your problem! Thanks.

Categories

Resources