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#
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:
- public void ReadDataFromFile(string fileName)
- {
- string Name;
- DateTime DOJ;
- var contents = System.IO.File.ReadAllText(fileName).Split('\n');
- var csv = from line in contents
- select line.Split(',').ToArray();
-
- int headerRows = 1;
- foreach (var row in csv.Skip(headerRows)
- .TakeWhile(r => r.Length > 1 && r.Last().Trim().Length > 0))
- {
- Name = row[0];
- DOJ = Convert.ToDateTime(row[1]) + TimeSpan.Parse(FormatTime(row[2]));
- }
- }
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);
- switch (timeFormat)
- {
- case ("AM"):
- outputTime = inputTime.Replace("AM", "");
- break;
- case ("PM"):
- int hours = 0;
- int.TryParse(inputTime.Replace("PM", ""), out hours);
- outputTime = (hours + 12).ToString();
- break;
- }
- return outputTime;
- }
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.