C#将12小时的时间解析为24小时的日期时间

时间:2015-04-26 18:18:01

标签: c# datetime datetime-format

我有一个12小时格式的小时列表:

2:30, 3:00, 4:00, 5:00, 6:00, 7:00, 8:00, 9:00, 10:00, 11:00, 12:00, 
1:00, 2:00, 3:00, 4:00, 5:00, 6:00, 7:00, 8:00, 9:00, 10:00, 11:00, 
12:00, 1:00, 2:00

第一个值2:30在夜晚。

如果我创建

List<DateTime> dates = new List<DateTime>();

我如何解析上面的小时数,以便创建一个List<DateTime>但是24小时格式的小时数?

事情是时间缺少am/pm信息所以我不知道如何解析它们24小时,否则将是重复。

1 个答案:

答案 0 :(得分:2)

那么,如果您的字符串数据是有序的(并且这是一个很大的if),您可以尝试使用此代码

string data = "2:30, 3:00, 4:00, 5:00, 6:00, 7:00, 8:00, 9:00, 10:00, 11:00, 12:00, 1:00, 2:00, 3:00, 4:00, 5:00, 6:00, 7:00, 8:00, 9:00, 10:00, 11:00, 12:00, 1:00, 2:00";
string[] parts = data.Split(',');

DateTime lastInput = DateTime.MinValue;
List<DateTime> dates = new List<DateTime>();
string currentAMPM = "AM";
foreach(string s in parts)
{
    DateTime temp;

    if(DateTime.TryParse(s + " " + currentAMPM, out temp))
    {
        if(temp < lastInput)
        {
            currentAMPM = (currentAMPM == "AM" ? "PM" : "AM");
            DateTime.TryParse(s + " " + currentAMPM, out temp);
        }
        dates.Add(temp);
        lastInput = temp;

    }
}