class declaration maintains the time in 24-hour format and ToString Method : ToString « Class Interface « C# / C Sharp






class declaration maintains the time in 24-hour format and ToString Method

class declaration maintains the time in 24-hour format and ToString Method



using System;

public class Time1
{
   private int hour; // 0 - 23
   private int minute; // 0 - 59
   private int second; // 0 - 59

   public void SetTime( int h, int m, int s )
   {
      hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); 
      minute = ( ( m >= 0 && m < 60 ) ? m : 0 );
      second = ( ( s >= 0 && s < 60 ) ? s : 0 );
   } 

   public string ToUniversalString()
   {
      return string.Format( "{0:D2}:{1:D2}:{2:D2}",
         hour, minute, second );
   } 
   public override string ToString()
   {
      return string.Format( "{0}:{1:D2}:{2:D2} {3}",
         ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ),
         minute, second, ( hour < 12 ? "AM" : "PM" ) );
   } 
}
public class Time1Test
{
   public static void Main( string[] args )
   {
      Time1 time = new Time1(); 
      Console.WriteLine( time.ToUniversalString() );
      Console.WriteLine( time.ToString() );

      time.SetTime( 13, 27, 6 );
      Console.WriteLine( time.ToUniversalString() );
      Console.WriteLine( time.ToString() );

      time.SetTime( 99, 99, 99 );
      Console.WriteLine( time.ToUniversalString() );
      Console.WriteLine( time.ToString() );
   }
}  
       








Related examples in the same category

1.demonstrates overriding the ToString() method to provide a custom string outputdemonstrates overriding the ToString() method to provide a custom string output
2.Illustrates how to override the ToString() methodIllustrates how to override the ToString() method
3.Demonstrate ToString()Demonstrate ToString()
4.Format data in ToString method.Format data in ToString method.
5.Overriding the ToString() MethodOverriding the ToString() Method
6..NET Frameworks Overview:Custom Object Formatting.NET Frameworks Overview:Custom Object Formatting