January 20, 2011

convert time 24 To 12 in asp.net

 If you want to convert time  24 format  To 12  am pm form in asp.net then you can try following method. You can write this method in common class in asp.net program then you can call this function by passing time variable in function parameter.


 public static string convert24To12(string time)  
 {  
       if (time.IndexOf(":") == -1)  
         return time;  
       string appendstring = "AM";  
       string strHr = time.Substring(0, time.IndexOf(":"));  
       string strMin = time.Substring(time.IndexOf(":") + 1);  
       int intHr = Convert.ToInt16(strHr);  
       if (intHr > 12)  
       {  
         appendstring = "PM";  
         intHr -= 12;  
       }  
       if (intHr == 12)  
       {  
         appendstring = "PM";  
       }  
       else if (intHr == 0)  
       {  
         intHr = 0;  
       }  
       return ((intHr < 10) ? "0" : "") + intHr + ":" + strMin + " " + appendstring;  
  }