将字符串转换为时间

我的时间是16:23:01。 我尝试使用DateTime.ParseExact ,但它不起作用。

这是我的代码:

 string Time = "16:23:01"; DateTime date = DateTime.ParseExact(Time, "hh:mm:ss tt", System.Globalization.CultureInfo.CurrentCulture); lblClock.Text = date.ToString(); 

我希望它在标签上显示为04:23:01 PM。

“16:23:01”与“hh:mm:ss tt”的模式不匹配 – 它没有上午/下午指示符,而且显然16不是12小时制。 您在解析部分中指定了该格式,因此您需要匹配现有数据的格式。 你要:

 DateTime dateTime = DateTime.ParseExact(time, "HH:mm:ss", CultureInfo.InvariantCulture); 

(注意不变的文化, 而不是当前的文化 – 假设你的输入真的总是使用冒号。)

如果要将其格式化hh:mm:ss tt ,则需要将该部分放入ToString调用中:

 lblClock.Text = date.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture); 

或者更好(IMO)使用“无论文化的长期模式是什么”:

 lblClock.Text = date.ToString("T", CultureInfo.CurrentCulture); 

还要注意hh是不寻常的; 通常你希望0-左键填充小于10的数字。

(还可以考虑使用我的Noda Time API,它具有LocalTime类型 – 只适用于“一天中的时间”。)

 string Time = "16:23:01"; DateTime date = DateTime.Parse(Time, System.Globalization.CultureInfo.CurrentCulture); string t = date.ToString("HH:mm:ss tt"); 

这为您提供了所需的结果:

 string time = "16:23:01"; var result = Convert.ToDateTime(time); string test = result.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture); //This gives you "04:23:01 PM" string 

您也可以使用CultureInfo.CreateSpecificCulture("en-US")因为并非所有文化都会显示AM / PM。