C # obtain the time range based on the current time, including this week, this month, and this quarter.

Source: Internet
Author: User

DateTime dt = DateTime. Now; // current time

DateTime startWeek = dt. AddDays (1-Convert. ToInt32 (dt. DayOfWeek. ToString ("d"); // Monday of the week
DateTime endWeek = startWeek. AddDays (6); // Sunday of the week

DateTime startMonth = dt. AddDays (1-dt. Day); // the beginning of this month
DateTime endMonth = startMonth. AddMonths (1). AddDays (-1); // End of the month
// DateTime endMonth = startMonth. AddDays (dt. AddMonths (1)-dt). Days-1); // End of the month

DateTime startQuarter = dt. AddMonths (0-(dt. Month-1) % 3). AddDays (1-dt. Day); // at the beginning of this quarter
DateTime endQuarter = startQuarter. AddMonths (3). AddDays (-1); // end of this quarter

DateTime startYear = new DateTime (dt. Year, 1, 1); // early this Year
DateTime endYear = new DateTime (dt. Year, 12, 31); // End of the Year

For yesterday, tomorrow, last week, last month, last quarter, and last year, you only need to combine AddDays (), AddMonths (), and AddYears.
Use of datetime in C #
// If you still don't understand it, you should understand how to display the day of the week in Chinese.
// Because DayOfWeek returns the day of the week of the number, we need to convert it into Chinese characters to facilitate reading. Some people may use the switch to compare them one by one. In fact, this is not so troublesome.
String [] Day = new string [] {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday "};
String week = Day [Convert. ToInt32 (DateTime. Now. DayOfWeek. ToString ("d")]. ToString ();

// Last week. Similarly, a week is 7 days. Last week is the week minus 7 days. The same is true for next week.
DateTime. No

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.