I have a varchar(5)
column in a table which contains the hour and minutes in 24 hour format time. I want to convert this 24 hour format to 12 hour format and finally embed this 12 hour format time into a DateTime Variable along with a Date value. Below is an example of demonstration.
For Example
8:18 should be converted into 8:18:00 AM and then should be embedded with a Date like 8/10/2012 8:18:50 AM to be able to store in DateTime column of DB.
22:20......10:20:00 PM.......8/10/2012 10:20:00 PM
The Date will not be current date it can be any date value like 8/8/2012 or 7/8/2012
The key to this code is to use the library function time. strptime() to parse the 24-hour string representations into a time. struct_time object, then use library function time. strftime() to format this struct_time into a string of your desired 12-hour format.
You can use SimpleDateFormat to format it the way you like, this works: SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); String str = sdf. format(new Date()); Also Android version of docs.
You can do something like this:
string input = "22:45";
var timeFromInput = DateTime.ParseExact(input, "H:m", null, DateTimeStyles.None);
string timeIn12HourFormatForDisplay = timeFromInput.ToString(
"hh:mm:ss tt",
CultureInfo.InvariantCulture);
var timeInTodayDate = DateTime.Today.Add(timeFromInput.TimeOfDay);
And now the important parts to take in consideration:
"H:m"
so it assumes a 24H value that does not use a zero to prefix single digits hours or minutes;"hh:mm:ss tt"
because it seems to be the format you desire, however you need to use CultureInfo.InvariantCulture
to be certain that you get a AM/PM designator that is in fact AM or PM. If you use another culture, the AM/PM designator may change;DateTime.Today
which returns the today date with a zeroed time and then we just add the time we read from input.To create the final date and time from another date you can instead use:
var timeInAnotherDate = new DateTime(2000, 1, 1).Add(timeFromInput.TimeOfDay);
Reference material:
create function dbo.COMBINE_DATE_TIME(
@DatePart DateTime, -- DateTime
@TimePart varchar(5)) -- Time
returns DateTime
as begin
return DATEADD(day, DATEDIFF(day,0,@DatePart),
CONVERT(DateTime,ISNULL(@TimePart,''),14))
end
go
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With