Detailed C # TimeSpan calculation time difference (interval) _c# tutorial

Source: Internet
Author: User
Tags current time datetime mscorlib number sign time interval spdate

The TimeSpan structure represents a time interval.

Namespaces: System Assembly: mscorlib (in mscorlib.dll)

Description: The 1.DateTime value type represents a specific date time from January 1, 01 0:0 0 seconds to A.D. December 31, 9999 23:59 59 seconds. Therefore, you can use the DateTime value type to describe any time within the imaginary range. The TimeSpan value contains a number of properties and methods that are used to access or process a TimeSpan value.

One of the five overloaded methods is structured TimeSpan (int days, int hours, int minutes, int seconds)

The following list covers a subset of the methods and attribute explanations

    • Add: Adds to another timespan value.
    • Days: Returns the value of the timespan that is calculated in the day.
    • Duration: Gets the absolute value of the timespan.
    • Hours: Returns the timespan value calculated in hours
    • Milliseconds: Returns the TimeSpan value computed 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: Subtracts another timespan value from it.
    • Ticks: Returns the number of tick for the timespan value.
    • Totaldays: Returns the number of days that the TimeSpan value represents.
    • Totalhours: Returns the number of hours represented by the timespan value.
    • TotalMilliseconds: Returns the number of milliseconds represented by the timespan value.
    • Totalminutes: Returns the number of minutes represented by the timespan value.
    • TotalSeconds: Returns the number of seconds that the timespan value represents.

Code instances

TimeSpan ts = new TimeSpan (12, 12, 11, 12, 21); int days = new TimeSpan (12, 12, 11, 12, 21).
      Days; TimeSpan Duration = new TimeSpan (-12, 12, 11, 12, 21). Duration ()///24 hour inverse value double totaldays = new TimeSpan (12, 12, 11, 12, 21).
      Totaldays; Double totalhours = new TimeSpan (2, 12, 11, 12, 21).
      totalhours; int hours = new TimeSpan (12, 12, 11, 12, 21).
      Hours; int minutes = new TimeSpan (12, 12, 11, 12, 21).
      Minutes;
      TimeSpan ts2 = new TimeSpan (1, 3, 01, 12, 21); TimeSpan ts2 = new TimeSpan (5, 3, 1, a);//this is also right TimeSpan Ts3 = new TimeSpan (5, 3,,,). A
      DD (TS); TimeSpan ts4 = new TimeSpan (4, 3, 01, 12, 21).
      Subtract (TS); TimeSpan ts5 = new TimeSpan (4, 3, 01, 12, 21). Subtract (TS).
      Duration (); TimeSpan negate = new TimeSpan (5, 3, 01, 12, 21).
      Negate ();
      DateTime Dtnow = DateTime.Now;
      Console.WriteLine (TS);
      Console.WriteLine (days);
      Console.WriteLine (duration); Console.WriteLine (ToTaldays);
      Console.WriteLine (totalhours);
      Console.WriteLine (hours);
      Console.WriteLine (minutes);
      Console.WriteLine (TS2);
      Console.WriteLine (TS+TS2);
      Console.WriteLine (TS3);
      Console.WriteLine ("Subtract:" +TS4);
      Console.WriteLine ("Duration:" + ts5);
      Console.WriteLine (TS-TS2);
      Console.WriteLine (negate);
      DateTime span = DateTime.Now.Add (TS2);
      TimeSpan spdate = Span-datetime.now; Long dateticks = DATETIME.NOW.ADD (TS2).
      Ticks;
      Console.WriteLine (span);
      Console.WriteLine (spdate);
 Console.WriteLine (Dateticks);

Negative

The above is a late date minus an earlier date, so each property value is a positive number, and if the earlier date is a later date, the property value is negative.

In ASP.net, two times subtract, get a TimeSpan instance, TimeSpan have some attributes: Days, Totaldays, Hours, Totalhours, Minutes, Totalminutes, Seconds, TotalSeconds, Ticks, note that there is no totalticks.

Give an example to explain

Time 1 is 2010-1-2 8:43:35;

Time 2 is 2010-1-12 8:43:34.

With time 2 minus time 1, get a TimeSpan instance.

Then 2 times 1 more 9 days 23 hours 59 minutes 59 seconds.

Then, days is 9,hours is 23,minutes is 59,seconds is 59.

To see Ticks,tick is a time period, indicating 100 nanoseconds, that is, one out of 10,000 seconds, then Ticks here to indicate the total difference between the number of periods, namely: 9 * 24 * 3600 * 10000000 + 23 * 3600 * 10000000 +59 * 6 0 * 10000000 + 59 * 10000000 = 8639990000000. 3600 is the number of seconds in an hour.

Totaldays is the Ticks conversion own number, namely: 8639990000000/(10000000 * 24 * 3600) = 9.99998842592593.

Totalhours is the conversion of Ticks into hours, that is: 8639990000000/(10000000 * 3600) = 239.999722222222.

Totalminutes is the conversion of Ticks into minutes, that is: 8639990000000/(10000000 * 60) = 14399.9833333333.

TotalSeconds is the conversion of Ticks into seconds, that is: 8639990000000/(10000000) = 863999.

Here are some common methods

function to find the last published time

public string Datestringfromnow (DateTime dt) 
{ 
TimeSpan 
span = Datetime.now-dt; 
if (span. Totaldays >) 
{return 
dt. ToShortDateString (); 
} 
else if (span. Totaldays >) 
{return 

"1 months ago"; 
} 
else if (span. Totaldays >) 
{return 
"2 weeks Ago"; 
} 
else if (span. Totaldays > 7) 
{return 
"1 weeks ago"; 
} 

else if (span. Totaldays > 1) 
{return 
string. Format ("{0} days ago", 
(int) Math.floor (span). totaldays)); 
} 
else if (span. Totalhours > 1) 
{return 
string. Format ("{0} hours ago", (int) Math.floor (span). totalhours)); 
} 
else if (span. Totalminutes > 1) 
{return 
string. Format ("{0} minutes ago", (int) Math.floor (span). totalminutes)); 
} 
else if (span. TotalSeconds >= 1) 
{return 
string. Format ("{0} seconds ago", 
(int) Math.floor (span). totalseconds)); 
} 

else {return 
"1 seconds Ago"; 

} 
}

Using TimeSpan in C # to calculate the difference of two times

You can add any one time unit between two dates.

private String DateDiff (DateTime DateTime1, datetime DateTime2)
{string DateDiff = null;
TimeSpan ts1 = new TimeSpan (datetime1.ticks);
TimeSpan ts2 = new 
TimeSpan (datetime2.ticks);
TimeSpan ts = ts1. Subtract (TS2). Duration ();
DateDiff = ts. Days.tostring () + "days" + TS. Hours.tostring () + "hour" + TS. Minutes.tostring () + "minutes" + TS. Seconds.tostring () + "seconds";
return dateDiff;
}
TimeSpan ts = date1-date2; 
Double ddays = ts. totaldays;//number of days with decimals, such as 1 days and 12 hours, the result is 1.5.

Like 1 days and 12 hours, the result is 1.5.

int ndays = ts. days;//integer days, 1 days 12 hours or 1 days 20 hours results are 1

<summary>
///Date comparison
///</summary>
///<param name= "Today" > Current date </param>
<param name= "Writedate" > Enter date </param>
///<param name= "n" > Compare days </param>
< Returns> is greater than the number of days returns true, less than return false</returns>
private bool Comparedate (string today, string writedate, int n)
{
DateTime = Convert.todatetime (today);
DateTime writedate = Convert.todatetime (writedate);
Writedate = Writedate.adddays (n);
if (today>= writedate) return
false;
else return
true;
}

When defining date data types, you must be aware of the following three points:

1. The date value must be enclosed in the number sign "#".

2. Date data in dates value is optional, if any must conform to the format "m/d/yyyy".

3. The time data in the date value is optional, if the date data must be separated by a space, and the minutes and seconds are separated by ":".

A The relationship and distinction between DateTime and TimeSpan:

DateTime and TimeSpan are visual Basic. NET, the difference is that dattime represents a fixed time, and timespan represents a time interval, that is, a period of time. In the program example described below, the timespan is used for the difference between the current time and the given time.

Two Common members in DateTime and TimeSpan and their descriptions:

The datetime structure and the timespan structure provide rich methods and properties,

Attribute description

  • Date gets the day part of this instance.
  • Day gets the date represented by this instance as the day ordinal of the month.
  • DayOfWeek gets the day of the week that this instance represents.
  • DayOfYear gets the date represented by this instance is the day ordinal of the year.
  • Hour gets the hour portion of the date represented by this instance.
  • Millisecond gets the millisecond portion of the date represented by this instance.
  • Minute gets the minute portion of the date represented by this instance.
  • Month gets the month portion of the date represented by this instance.
  • Now creates a DateTime instance, which is the current local date and time on this computer.
  • Second gets the second portion of the date represented by this instance.
  • TimeOfDay gets the time of the day for this instance.
  • Today gets the current date.
  • Year gets the years portion of the date represented by this instance.
  • Add adds the value of the specified timespan to the value of this instance.
  • AddDays adds the specified number of days to the value of this instance.
  • AddHours adds the specified number of hours to the value of this instance.
  • Addmilliseconds adds the specified number of milliseconds to the value of this instance.
  • AddMinutes adds the specified number of minutes to the value of this instance.
  • Addmonths adds the specified number of months to the value of this instance.
  • AddSeconds adds the specified number of seconds to the value of this instance.
  • Addyears adds the specified number of years to the value of this instance.
  • DaysInMonth returns the number of days of the specified month in the specified year.
  • Isleapyear returns whether the specified year is an indication of leap years.
  • Parse converts the specified string representation of a date and time to its equivalent datetime instance.
  • Subtract subtracts the specified time or duration from this instance.
  • Tolongdatestring converts the value of this instance to its equivalent long date string representation.
  • Tolongtimestring converts the value of this instance to its equivalent long time string representation.
  • Toshorttimestring converts the value of this instance to its equivalent short time string representation.
  • ToShortDateString converts the value of this instance to its equivalent short date string representation.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.