Fahad Abid Janjua
Fahad Abid Janjua

Reputation: 1024

Conversion to Time 12 hour Format From String containing Time in 24 hour format

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

Upvotes: 5

Views: 13720

Answers (4)

ARC
ARC

Reputation: 1081

            string fromTime = Convert.ToStr(reader["TimeFrom"]);
            string toTime = Convert.ToStr(reader["TimeTo"]);
            item.Time=DateTime.Parse(fromTime,CultureInfo.CurrentCulture).ToString("hh:mm tt");

here the property of your model(item.Time here) should be the string.

Upvotes: 0

João Angelo
João Angelo

Reputation: 57718

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:

  • The format for parsing uses "H:m" so it assumes a 24H value that does not use a zero to prefix single digits hours or minutes;
  • The format for printing uses "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;
  • The full date and time is constructed based on 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:

Upvotes: 11

Himanshu
Himanshu

Reputation: 32612

string strDate = DateTime.ParseExact("8:18","HHmm",CultureInfo.CurrentCulture).ToString("hh:mm tt");

Upvotes: 0

Matt Varblow
Matt Varblow

Reputation: 7901

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

Upvotes: 1

Related Questions