I am receiving data representing a time slot from a service as a string in the form of:
1500-1600
This meaning 3pm to 4pm.
I will have a list of these e.g.
1200-1300
1300-1400
1400-1500
and I have to represent this in the UI as
12pm – 1pm
1pm – 2pm
2pm – 3pm
Unfortunately this list could be in a random order.
My question is is there any way of using the DateTime object to be able to convert a 24 hour time to a 12 hour time and also is there a way of ordering times in order?
At the moment I am feeling I will have to write a custom parsing function but wondering if anyone knows how to do this better? or could advise on how they would achieve this.
If you have the four digit strings (1200, 1300) and it will always be four digits (e.g. 9 am is 0900) then you can call the static
ParseExactmethod on theDateTimestructure like so:formatInfois anIFormatProviderinterface implementation.If you have a three digit string, then you can use this:
However, I would recommend using a four-digit string because of the ambiguity presented with a time like ‘121’.
From there, if you want to output am/pm, etc, etc, you would just call the
ToStringmethod, passing the following format: