-3

I would like to know how to calculate the remaining days of the month e.g (15 Feb 2017 to 28 Feb 2017) without the use of a datetimepicker set at 28 Feb 2017.

Here are my codes for subtraction of 2 datetimepicker:

 DateTime startDate =
     (DateTime)dateTimePicker2.Value;

 DateTime endDate =
     (DateTime)dateTimePicker1.Value;

 TimeSpan ts = endDate.Subtract(startDate);

 textBox10.Text = ts.Days.ToString();`
sa77
  • 3,563
  • 3
  • 24
  • 37
EGS
  • 55
  • 1
  • 7

3 Answers3

0

Here are the steps you need to go through:

  • take your current date
  • use DateTime.AddMonths() to generate a new date one month from your current date
  • create a new date that uses 1 for the day, and the month and year from the future date you just worked out
  • subtract your current date from the future date, this will give you a Timespan which contains the number of days difference

You can use the closely related question Calculate difference between two dates (number of days)? as a guide.

slugster
  • 49,403
  • 14
  • 95
  • 145
0

Here is an example, but you can use the Value property from your DateTimePicker instead. DateTime.DaysInMonth(int year, int month) is a helpful method.

DateTime beginDate = new DateTime(2017, 2, 15);
var daysLeft = DateTime.DaysInMonth(beginDate.Year, beginDate.Month) - beginDate.Day;
Console.WriteLine("days from Feb 15 to Feb 28: {0}", daysLeft);

Output:

days from Feb 15 to Feb 28: 13

Poosh
  • 532
  • 2
  • 10
  • 25
  • Why the downvote please? – Poosh Aug 15 '17 at 02:08
  • @L.B, the question wasn't off-topic or asking for opinions/advice. The asker obviously wanted to find the last day of a month. I'm using the same object they used in their current code. – Poosh Aug 15 '17 at 02:20
-1

You can try:

DateTime dt = DateTime.Now;
int days = dt.AddDays(1 - dt.Day).AddMonths(1).AddDays(-1).Day - dt.Day;
Fabien
  • 4,862
  • 2
  • 19
  • 33
yacc
  • 2,915
  • 4
  • 19
  • 33