简体   繁体   English

如何将字符串转换为时间字符串 C#

[英]How to convert string to time string C#

How can I convert the following如何转换以下内容

string Time = "2324";字符串时间=“2324”; string Time = "1024";字符串时间=“1024”;

In the first case the converted value should be another string "11:24 PM".在第一种情况下,转换后的值应该是另一个字符串“11:24 PM”。 The second case should be "10:24 AM".第二种情况应该是“10:24 AM”。

I tried Date.ParseExact(Time,"hh:mm tt",CultureInfo.InvariantCulture) That solves it when the time is less than 12:00PM.我试过 Date.ParseExact(Time,"hh:mm tt",CultureInfo.InvariantCulture) 当时间小于 12:00PM 时解决它。 But when it is "2324", I get 23:24 PM when I actually need 11:24 PM但是当它是“2324”时,当我实际需要 11:24 PM 时,我会得到 23:24 PM

Method expects time to be always 4 characters方法期望时间总是 4 个字符

    static string ParseTime(string time)
    {
        if (int.TryParse(time.Substring(0, 2), out int hrs) && int.TryParse(time.Substring(2), out int min))
        {
            return new DateTime(2001, 1, 1, hrs, min, 0).ToString("hh:mm tt", CultureInfo.InvariantCulture);
        }
        // throw exception or return empty;
        return string.Empty;
    }

Fiddle小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM