+4

How can I make this Military Time code simpler?

https://code.sololearn.com/cRv5vJSAQjVB/?ref=app This was my first attempt at a medium challenge and I feel like I did it rather cleanly, but there's something about it that bugs the crap out of me. Is there some key thing I'm missing here that could remove most of this code, or do codes generally get so unruly?

1/5/2020 7:39:48 AM

{ Aza }

11 Answers

New Answer

+4

Actually, your code is pretty great as it is, it's by far the best code _I've seen_ for this problem. Better than mine, which, I agree, is illegible even to me by tomorrow, while yours was clear at a first glance.

+3

My solution 😀 namespace SoloLearn { class Program { static void Main(string[] args) { string s = Console.ReadLine(); var b= Convert.ToDateTime(s); Console.WriteLine(Kajman.ChangeDate(b)); Console.ReadKey(); } } public class Kajman { public static string ChangeDate(DateTime? s) { return s.Value.ToString("HH:mm"); } } }

+2

You can replace one line IF's with a shorthand For example: if(amPm == "PM" && hoursInt < 12) { hoursInt += 12; } Change to: if(amPm == "PM" && hoursInt < 12) hoursInt += 12;

+2

Kajman actually clean af

+2

{ Aza } I think the code is good. Rather than converting everything to Int, I manipulated the string, but it ended up almost the exact number of lines that you have. I like that DateTime API. I found one in Java that was very similar. I didn't know about the one in C#. So I just learned something 🤯 Paul Jacobs idea for if simplification is great. further to that idea, renaming the amPm to isPM or simply pm would add to readability.

+1

I think it is basically good, but you could improve on details. For instance, you could change string amPm to a Boolean. And make it true if the input string contains a 'P'. A line like this: if(amPm == "PM" && hoursInt < 12) would be: if(amPm && hoursInt < 12) And you don't need indexSpace anymore.

+1

you can use the c# datetime API string timeStr = Console.ReadLine(); // convert am,pm to 24 hour format DateTime dt = DateTime.ParseExact(timeStr, "h:mm tt", null); Console.WriteLine(dt.ToString("HH:mm"));

+1

Birdie it is just a DateTime object its not an "API". It would have been an APi if that object communicated with far away server (for example) and got from it the result each time you ran a specific function.

+1

// I think I'd write it like this: string [] s = Console.ReadLine().Split(); string [] t = s[0].Split(':'); int h = int.Parse(t[0]); if(s[1] == "PM") h += 12; else if(h == 12) h = 0; Console.WriteLine($"{h:00}:{t[1]}"); // EDIT: there was a mistake on the line Console.WriteLine(), I corrected it https://code.sololearn.com/cj93DLXZ9ihv

+1

Ok, I'm still learning so I don't really understand the Split and Parse functions, and just started learning arrays. At my current state those codes are illegible to me, but I'm learning each day so at least now I know what to research as far as strings go.

0

Simpler than the c++ version