开发者

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

开发者 https://www.devze.com 2023-02-10 17:48 出处:网络
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

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 h开发者_StackOverflowelp beforehand.


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");


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");
    }


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");


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消