C # Some time processing methods, such as days, hours, minutes, and months

Source: Internet
Author: User
Tags dateformat

// Obtain the last day of a month
// Method 1: calculate the number of days of the month, and the number of days plus the year + month. The example shows the last day of the month.
Private void getlastdateformonth (datetime dtstart, out datetime dtend)
{
Int dtyear, dtmonth;
Dtstart = datetime. now;
Dtyear = dtstart. Year;
Dtmonth = dtstart. month;
Int monthcount = datetime. daysinmonth (dtyear, dtmonth); // calculates the number of days in a month.
Dtend = convert. todatetime (dtyear. tostring () + "-" + dtmonth. tostring () + "-" + monthcount );
}
// Method 2: retrieve the first day of the next month.
Private void getlastdateformonth (datetime dtstart, out datetime dtend)
{
Int dtyear, dtmonth;

Dtstart = datetime. Now. addmonths (1); // Add 1 to the month
Dtyear = dtstart. Year;
Dtmonth = dtstart. month;
Dtend = convert. todatetime (dtyear. tostring () + "-" + dtmonth. tostring () + "-" + "1 "). adddays (-1); // retrieve the first day of the next month for one day
}

Ii. Calculation of time difference
Method 1: Use timespan and introduce the usage of timespan.
Related attributes and functions
Add: adds the value to another timespan value.
Days: returns the timespan value calculated by the number of days.
Duration: gets the absolute value of timespan.
Hours: returns the hourly timespan value.
Milliseconds: returns the timespan value in milliseconds.
Minutes: returns the timespan value calculated in minutes.
Negate: returns the opposite number of the current instance.
Seconds: returns the timespan value calculated in seconds.
Subtract: Subtract another timespan value from it.
Ticks: the number of tick values returned for timespan.
Totaldays: returns the number of days indicated by the timespan value.
Totalhours: returns the number of hours represented by the timespan value.
Totalmilliseconds: the number of milliseconds in which the timespan value is returned.
Totalminutes: returns the number of minutes represented by the timespan value.
Totalseconds: returns the number of seconds represented by the timespan value.
Simple Example:
Datetime d1 = new datetime );
Datetime D2 = new datetime );
Timespan D3 = d2.subtract (D1 );
Lbtime. Text = "difference :"
+ D3.days. tostring () + "day"
+ D3.hours. tostring () + "hour"
+ D3.minutes. tostring () + "Minute"
+ D3.seconds. tostring () + "seconds ";
Method 2: Use the datediff function in SQL
Usage: datediff (datepart, startdate, enddate)
It can help you get the time difference in various forms you want, such as how many days, how many hours, and how many minutes are separated. The specific format is as follows:

Abbreviation of date
Year YY, yyyy
Quarter QQ, Q
Month mm, m
Dayofyear dy, y
Day DD, d
Week wk, WW
Hour HH
Minute Mi, n
Second SS, S
Millisecond MS

For example, datediff (MI, dtoptime, dtend) can retrieve the total number of minutes of time difference between them, which has been converted for you. It is particularly useful for specifying the unit, time, minute, and second.

3 calculate the difference between two days of working days (reprinted: http://wrfwjn.blog.hexun.com/482517_d.html)

/// <Summary>
/// Calculate the number of working days between two dates
/// </Summary>
/// <Param name = "dtstart"> Start date </param>
/// <Param name = "dtend"> end date </param>
/// <Returns> int </returns>
Public int calculateworkingdays (datetime dtstart, datetime dtend)
{
Int COUNT = 0;
For (datetime dttemp = dtstart; dttemp <dtend; dtemp = dttemp. adddays (1 ))
{
// If (dttemp. dayofweek! = Dayofweek. Saturday & dttemp. dayofweek! = Dayofweek. Sunday)
//{
// Count ++;
//}
Count ++;
}
Return count;
}
Datetime is the built-in event type, and timespan is the built-in event interval type.
Perform operations on two datetime-type variables to obtain data of the timespan type.
Datetime. Now is a read-only attribute that returns the current time, type: datetime
Timespan: Calculate the interval between two specified dates based on the input date.
Syntax: String timespan ('escape characters', 'compared date', 'destination compared date ')

Return Value: character

Parameter description:

Escape Character: Characters of the input type with different formatting characters, as shown in the content description. The formatting characters in the input characters are formatted and output. Other characters that are not formatted are output according to the corresponding position. 'Date to be compared ': the input type is a character and the content of the character in the date format to be compared. 'Destination comparison date': the input type is a character used to compare the content of the characters in the target date format.

Description: Calculate the interval between two specified dates based on the input date.

Escape Character Description: T: obtains the difference value represented by the difference scale between two dates. (Positive or negative) D: returns the whole number of days for the difference between two dates. (Positive or negative) h: obtains the hour of the difference between two dates. (Positive or negative) U: returns the number of milliseconds for the difference between two dates. (Positive or negative) M: returns the number of minutes of the difference between two dates. (Positive or negative) S: returns the integer number of seconds between two dates. (Positive or negative) D: gets the difference between two dates in the whole day and the decimal part of the day. (Positive or negative) h: obtains the difference between two dates expressed in the fractional part of the hour and hour. (Positive or negative) U: obtains the difference between the entire millisecond count and the fractional part of the millisecond between two dates. (Positive or negative) M: gets the difference between two dates in the whole minute and minute decimal part. (Zheng
Number or negative number) S: returns the difference between two dates in the integer and second decimal part. (Positive or negative)

Reprinted from: http://blog.csdn.net/wcmtu/archive/2009/01/03/3696622.aspx

Bytes -------------------------------------------------------------------------------------------------------

Number of months (d1.year-d2.year) * 12 + d1.month-d2.month

Totalday. Text = (datetime. parse (day1edit. Text)-datetime. parse (day2edit. Text). totaldays. tostring (); // different days

Totalhour. Text = (datetime. parse (day1edit. Text)-datetime. parse (day2edit. Text). totalhours. tostring (); // hours of difference

Totalminute. Text = (datetime. parse (day1edit. Text)-datetime. parse (day2edit. Text). totalminutes. tostring (); // minute of difference

/// <Summary>
/// Get the specified format of two dates
/// </Summary>
/// <Param name = "dt1"> date 1 </param>
/// <Param name = "dt2"> date 2 </param>
/// <Param name = "dateformat"> interval format: Y: year M: month D: day h: hour M: minute second fff: millisecond ffffff: subtle fffffff: 100 ml </param>

/// <Returns> long interval </returns>
Public static long getintervalof2datetime (datetime dt1, datetime dt2, string dateformat)

{
Try
{
Long interval = dt1.ticks-dt2.ticks;
Datetime dT11;
Datetime dt22;

Switch (dateformat)
{
Case "fffffff": // 100 ml
Break;
Case "ffffff": // subtle
Interval/= 10;
Break;
Case "fff": // millisecond
Interval // = 10000;
Break;
Case "S": // second
Interval // = 10000000;
Break;
Case "M": // minute limit
Interval // = 600000000;
Break;
Case "H": // hour
Interval // = 36000000000;
Break;
Case "D": // day
Interval // = 864000000000;
Break;
Case "M": // month
DT11 = (dt1.compareto (dt2)> = 0 )? Dt2: dt1;
Dt22 = (dt1.compareto (dt2)> = 0 )? Dt1: dt2;
Interval =-1;
While (dt22.compareto (dT11)> = 0)
{
Interval ++;
DT11 = dt11.addmonths (1 );
}
Break;
Case "Y": // year
DT11 = (dt1.compareto (dt2)> = 0 )? Dt2: dt1;
Dt22 = (dt1.compareto (dt2)> = 0 )? Dt1: dt2;
Interval =-1;
While (dt22.compareto (dT11)> = 0)
{
Interval ++;
DT11 = dt11.addmonths (1 );
}
Interval/= 12;
Break;
}
Return interval;
}
Catch (exception ex)
{
String error = ex. message;
Return 0;
}
}

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.