views:

722

answers:

5

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.

A: 

Custom parsing should be trivial. Split at the '-' and parse each time; remove the last two digits to get the minutes, the remaining one or two to get the hour, and you're done.

If you need them in order, sort them.

Update the question or leave a comment if you need more help than this.

MarkusQ
+10  A: 

I'll assume you know how to split the times into "1400" and "1500". The easiest way (IMO) would be to use

DateTime.ParseExact(input, "HHmm", CultureInfo.InvariantCulture)

That will return a DateTime with today's date and the given time. You can then format that DateTime however you want.

Alternatively, you could parse "1400" as an integer, then find the minutes and hours using Math.DivRem, dividing by 100. Personally I prefer to use DateTime though.

Jon Skeet
Thanks. The following from casperOne's post is very helpful also string ampm = dt.ToString("htt")
w4ymo
+1  A: 

I would first split on the " - " to get the two different strings, then use the DateTime.ParseExact() method to look into converting it to a useable datetime object

Josh W.
+2  A: 

If you have the four digit string (1200, 1300) and it will always be four digits (e.g. 9 am is 0900) then you can call the static ParseExact method on the DateTime structure like so:

DateTime dt = DateTime.ParseExact(time, "HHmm", formatInfo);

formatProvider is an IFormatProvider implementation.

If you have a three digit string, then you can use this:

DateTime dt = DateTime.ParseExact(time, "Hmm", formatInfo);

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 ToString, passing the following format:

string ampm = dt.ToString("htt");
casperOne
A: 

Try this to convert and output to whatever format you need ` Dim aDateTime As DateTime aDateTime = DateTime.ParseExact(input, "HHmm", Nothing) Dim outputToDesiredFormat As String = dt.ToString("h:mm tt")

`

Drakinfar