cycero
cycero

Reputation: 4761

Converting AM/PM time to standard time format hh:mm in C#

In my ASP.NET web form I have 3 fields - hour, minute and am/pm drop down. How can I get the values of those 3 fields into one variable and then convert the am/pm hour to standard 24 hour time like 05:20PM = 17:20. This needs to be done in C#.

Thanks for the help beforehand.

Upvotes: 1

Views: 12223

Answers (4)

JonC
JonC

Reputation: 978

string hour = hourField.Text
string minute = minuteField.Text

string AMPM = ddl.SelectedItem.ToString();

//AMPM is either "AM" or "PM"
timeString = hour + ":" + minute + " " + AMPM

//the procued string in timeString is e.g. "10:45 PM"
DateTime time = DateTime.Parse(timeString);

You have to observe that 12:00AM is midnight and should produce 00:00. The fact that 12:00AM is one hour before 1:00AM, using modulo you would have to do it like:


if(hour == 12)hour = 0;
if(AMPM == "PM") hour = (hour % 12) + 12;

Upvotes: 1

Greg Buehler
Greg Buehler

Reputation: 3894

Are you saying your starting out with separate values for hour, minute, and am/pm?

    public string Get24HourTime(int hour, int minute, string ToD)
    {           
        int year = DateTime.Now.Year;
        int month = DateTime.Now.Month;
        int day = DateTime.Now.Day;
        if (ToD.ToUpper() == "PM") hour = (hour  % 12) + 12;

        return new DateTime(year, month, day, hour, minute, 0).ToString("HH:mm");
    }

Upvotes: 2

Oleg Rudckivsky
Oleg Rudckivsky

Reputation: 930

You can put dummy year, month and day if only time is needed.

DateTime time = new DateTime(year, month, day, hour, minute, second);
string time = time.ToString("HH:mm");

Upvotes: 1

KeithS
KeithS

Reputation: 71565

var hour = int.Parse(ddlHour.SelectedValue);
var min = int.Parse(ddlMin.SelectedValue);
var ampm = ddlAmPm.SelectedValue;

hour = ampm == "AM" ? hour : (hour % 12) + 12; //convert 12-hour time to 24-hour

var dateTime = new DateTime(0,0,0, hour, min, 0);
var timeString = dateTime.ToString("HH:mm");

Upvotes: 4

Related Questions