Remove AM PM from Time String using C#

It’s always fun as well as frustration at times working with DateTime in C#.

While working with one of the application, I had a requirement to remove the trailing AM/PM from time string which we were reading from as .csv file.

If anyone out there with similar requirement, he/she can straight away refer to this post and no need to think on writing the logic. So thought of sharing it.

Remove AM PM from Time String using CSharp
                                           Remove AM PM from Time String using C#


CSV File:

Name

DOJ

Check in Time

Dipendra

4/15/2016

9:00:00 AM

Mahesh

4/12/2016

2:30:00 PM

Code Snippets:

Function to read data from input file:

  1. public void ReadDataFromFile(string fileName)   
  2. {  
  3.  string Name;  
  4.  DateTime DOJ;  
  5.  var contents = System.IO.File.ReadAllText(fileName).Split('\n');  
  6.  var csv = from line in contents  
  7.            select line.Split(',').ToArray();  
  8.    
  9.  int headerRows = 1;  
  10.  foreach (var row in csv.Skip(headerRows)  
  11.          .TakeWhile(r => r.Length > 1 && r.Last().Trim().Length > 0))  
  12.  {  
  13.      Name = row[0];  
  14.      DOJ = Convert.ToDateTime(row[1]) + TimeSpan.Parse(FormatTime(row[2]));  
  15.  }  
  16. }  
Function to format time by stripping out AM/PM string:
  1. protected string FormatTime(string inputTime)  
  2.     {  
  3.         string outputTime = string.Empty;  
  4.         string timeFormat = inputTime.Substring(inputTime.Length - 2);  
  5.         switch (timeFormat)  
  6.         {  
  7.             case ("AM"):  
  8.                 outputTime = inputTime.Replace("AM""");  
  9.                 break;  
  10.             case ("PM"):  
  11.                 int hours = 0;  
  12.                 int.TryParse(inputTime.Replace("PM"""), out hours);  
  13.                 outputTime = (hours + 12).ToString();  
  14.                 break;  
  15.         }  
  16.         return outputTime;  
  17.     }  
Hope this post was useful and saved your time.

What do you think?

Dear Reader,

If you have any questions or suggestions, please feel free to email us or put your thoughts as comments below. We would love to hear from you. If you found this post or article useful then please share along with your friends and help them to learn.

Happy Learning.