Remove AM PM from Time String using CSharp
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 C#
||Check in Time
Function to read data from input file:
public void ReadDataFromFile(string fileName)
var contents = System.IO.File.ReadAllText(fileName).Split('\n');
var csv = from line in contents
int headerRows = 1;
foreach (var row in csv.Skip(headerRows)
.TakeWhile(r => r.Length > 1 && r.Last().Trim().Length > 0))
Name = row;
DOJ = Convert.ToDateTime(row) + TimeSpan.Parse(FormatTime(row));
Function to format time by stripping out AM/PM string:
protected string FormatTime(string inputTime)
string outputTime = string.Empty;
string timeFormat = inputTime.Substring(inputTime.Length - 2);
outputTime = inputTime.Replace("AM", "");
int hours = 0;
int.TryParse(inputTime.Replace("PM", ""), out hours);
outputTime = (hours + 12).ToString();
Hope this post was useful and saved your time.
What do you think?
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.