Compare TimeSpan
In this chapter you will learn:
Compare two TimeSpan values
We can use >, < operators to compare two TimeSpan values directly.
using System;// j a v a 2s . co m
using System.Text;
class Sample
{
public static void Main()
{
TimeSpan ts = TimeSpan.FromDays(10) - TimeSpan.FromSeconds(1); // 9.23:59:59
TimeSpan ts2 = TimeSpan.FromHours(2) + TimeSpan.FromMinutes(30);
Console.WriteLine(ts < ts2);
Console.WriteLine(ts > ts2);
}
}
The output:
Equals
using System;//java 2s . co m
class MainClass
{
static void Main( )
{
CreateTimeSpan( 999999L );
}
static void CreateTimeSpan( long ticks )
{
TimeSpan interval = new TimeSpan();
Console.WriteLine(interval.Equals(TimeSpan.Zero));
}
}
Comparison operator and TimeSpan
using System;// j a va2 s . c o m
class Main
{
const string dataFmt = "{0,34} {1}" ;
static void CompareTimeSpans( TimeSpan Left, TimeSpan Right, string RightText )
{
Console.WriteLine( dataFmt, "Right: " + RightText, Right );
Console.WriteLine( dataFmt, "Left == Right", Left == Right );
Console.WriteLine( dataFmt, "Left > Right", Left > Right );
Console.WriteLine( dataFmt, "Left >= Right", Left >= Right );
Console.WriteLine( dataFmt, "Left != Right", Left != Right );
Console.WriteLine( dataFmt, "Left < Right", Left < Right );
Console.WriteLine( dataFmt, "Left <= Right", Left <= Right );
}
static void Main( )
{
TimeSpan Left = new TimeSpan( 2, 0, 0 );
CompareTimeSpans( Left, new TimeSpan( 0, 120, 0 ), "TimeSpan( 0, 120, 0 )" );
}
}
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Date, Time, TimeZone