将AM / PM时间转换为标准时间格式hh:mm in C#

时间:2011-02-16 19:09:35

标签: c# time

在我的ASP.NET网络表单中,我有3个字段 - 小时,分钟和上午/下午。如何将这3个字段的值转换为一个变量,然后将am / pm小时转换为标准的24小时时间,如05:20 PM = 17:20。这需要在C#中完成。

事先感谢您的帮助。

4 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

你是说你的小时,分​​钟和上午/下午的单独值开始?

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

答案 2 :(得分:1)

如果只需要时间,你可以把虚拟年,月和日。

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

答案 3 :(得分:1)

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

您必须注意,凌晨12:00是午夜,应该生成00:00。上午12:00是凌晨1点前一小时的事实,使用模数你必须这样做:


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