I am trying to solve the Time Conversion problem of HackerRank in C#. Basically, you are given a string in AM/PM format and you need to convert it to military time (24 hours time format).
The sample input is: 07:05:45PM Expected output is: 19:05:45
I have tried "DateTime.Parse(timeString)", the solution proposed in this thread, but it gives me wrong answer (I get 07:05:45 as output, it only removes the AM/PM):
DateTime dt = DateTime.Parse("01:00 PM");
dt.ToString("HH:mm");
I searched a little more in DateTime library and also tried DateTime.TryParseExact(), but I get the same result:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Globalization;
class Solution {
static string timeConversion(string inputTimeString)
{
DateTime outputTime;
bool res = DateTime.TryParseExact(
inputTimeString,
"hh:mm:sstt",
System.Globalization.CultureInfo.InvariantCulture,
DateTimeStyles.None,
out outputTime);
//Console.WriteLine("res: " + res);
return outputTime.ToString("hh:mm:ss");
}
static void Main(string[] args)
{
TextWriter tw = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
string s = Console.ReadLine();
string result = timeConversion(s);
tw.WriteLine(result);
tw.Flush();
tw.Close();
}
}