C # obtain the first day of the current month and the last day to calculate the number of days between the two dates,

Source: Internet
Author: User

C # obtain the first day of the current month and the last day to calculate the number of days between the two dates,

Obtain the first and last days of the current month.

DateTime now = DateTime. Now; DateTime firstDay = new DateTime (now. Year, now. Month, 1); DateTime lastDay = firstDay. AddMonths (1). AddDays (-1 );

Calculate the number of days between two dates

DateTime start = firstDay; DateTime end = lastDay; TimeSpan ts = end. Subtract (start); ts. Days;

========================================================== ======================================

Thanks to the new ideas provided on the second floor, we will do a subtraction and an addition. You can see the code written on the second floor.

Date. AddDays (double) (1-Date. Day ))

Easy to understand, but easy to disassemble

Private void button#click (object sender, EventArgs e) {DateTime date = DateTime. now; double day = 1-date. day; DateTime firstDay = date. addDays (double) (1-date. day); MessageBox. show (firstDay. toShortDateString ());}

Now my date is, the value of the variable day is-18

AddDays is defined as "adding the specified number of days to the value of this instance". In this way, 19 + (-18) = 1. The idea is quite good, I sincerely thank @ diyun for his new thoughts.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.