I am creating an application that needs to allow the user to input a 4-digit text string (ex. 1330 or 0100) and convert that input to the time of day including AM/PM.
examples 1330 = 1:30 PM; 0130 = 1:30 AM
I am unsure what the best way to go about this would be. I am thinking to use a select case or nested ifs; however, I feel as if there is probably a better, quicker way to convert this. Any help will be much appreciated. Thank you in advance.
One possibility would be to use the DateTimePicker control from the Extended WPF Toolkit or create your own simple user control with for example two fields for the hour and minute parts.
If you want to create your own solution:
The code to parse the user input string:
private Function parseTime(ByRef hours as String) as String
' TODO: error handling
Dim timeStamp as String = String.Format("{0} {1}:{2}", System.DateTime.Now.ToShortDateString(), hours.Substring(0, 2),hours.Substring(2, 2))
Dim dateTime as DateTime
if (DateTime.TryParse(timeStamp, dateTime)) then
return String.Format("{0}{1}", dateTime.ToString("hh:mm", CultureInfo.InvariantCulture), dateTime.ToString("tt", CultureInfo.InvariantCulture))
end if
return String.Empty
end Function
Usage:
Dim hoursPM as String = "1330"
Dim hoursAM as String = "0130"
Console.WriteLine(parseTime(hoursPM))
Console.WriteLine(parseTime("errr")) 'empty string indicates error
Console.WriteLine(parseTime(hoursAM))
And the output:
01:30PM
01:30AM
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.