C # Inside comparison time size three ways

Source: Internet
Author: User
Tags comparison datetime tostring

1, compare the time size of the experiment

string  st1="12:13";
string  st2="14:14";
DateTime  dt1=Convert.ToDateTime(st1);
DateTime  dt2=Convert.ToDateTime(st2);
DateTime  dt3=DateTime.Now;
if(DateTime.Compare(dt1,dt2)>0)
msg.Text=st1+">"+st2;
else
msg.Text=st1+"<"+st2;
msg.Text+="\r\n"+dt1.ToString();
if(DateTime.Compare(dt1,dt3)>0)
msg.Text+="\r\n"+st1+">"+dt3.ToString();
else
msg.Text+="\r\n"+st1+"<"+dt3.ToString();

2, calculate the two time difference function, return the absolute value of the time lag:

private  string  DateDiff(DateTime  DateTime1,DateTime  DateTime2)
{
string  dateDiff=null;
try
{
TimeSpan  ts1=new   TimeSpan(DateTime1.Ticks);
TimeSpan  ts2=new   TimeSpan(DateTime2.Ticks);
TimeSpan  ts=ts1.Subtract(ts2).Duration();
dateDiff=ts.Days.ToString()+"天"
+ts.Hours.ToString()+"小时"
+ts.Minutes.ToString()+"分钟"
+ts.Seconds.ToString()+"秒";
}
catch
{
}
return  dateDiff;
}

3, the realization calculates datetime1-36 day =datetime2 function

TimeSpan  ts=new  TimeSpan(40,0,0,0);
DateTime  dt2=DateTime.Now.Subtract(ts);
msg.Text=DateTime.Now.ToString()+"-"+ts.Days.ToString()+"天\r\n";
msg.Text+=dt2.ToString();

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.