I am new to C#. I just created a method where I can convert a string with the format HH:MM AM/PM to minutes. I was wondering if there is a better or more effective way to achieve the same result.
static void Main(string[] args)
{
string time1 = "11:15 AM";
string time2 = "11:15 PM";
calculateTimeInMinutes(time1);
calculateTimeInMinutes(time2);
void calculateTimeInMinutes(string currentTime)
{
if (currentTime.Contains("PM"))
{
int hours = Convert.ToInt32(currentTime.Substring(0, 2));
int HoursInminutes = (12 + (hours % 60)) * 60;
string minutesInString = currentTime.Split(':')[1];
int minutes = Convert.ToInt32(minutesInString.Remove(2));
int totalMinutes = HoursInminutes + minutes;
Console.WriteLine(totalMinutes);
}
else
{
int hours = Convert.ToInt32(currentTime.Substring(0, 2));
int HoursInminutes = (hours % 60) * 60;
string minutesInString = currentTime.Split(':')[1];
int minutes = Convert.ToInt32(minutesInString.Remove(2));
int totalMinutes = HoursInminutes + minutes;
Console.WriteLine(totalMinutes);
}
}
Console.ReadKey();
}
}
hours % 60
part? This baffles me completely: for any time between00:00
and23:59
it will do nothing. \$\endgroup\$