Convert string to Time

前端 未结 4 602
忘了有多久
忘了有多久 2021-02-01 13:23

I have a time that is 16:23:01. I tried using DateTime.ParseExact, but it\'s not working.

Here is my code:

string Time = \"16:23:01\"; 
Date         


        
相关标签:
4条回答
  • 2021-02-01 14:01

    This gives you the needed results:

    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
    

    You could also use CultureInfo.CreateSpecificCulture("en-US") as not all cultures will display AM/PM.

    0 讨论(0)
  • 2021-02-01 14:03

    "16:23:01" doesn't match the pattern of "hh:mm:ss tt" - it doesn't have an am/pm designator, and 16 clearly isn't in a 12-hour clock. You're specifying that format in the parsing part, so you need to match the format of the existing data. You want:

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

    (Note the invariant culture, not the current culture - assuming your input genuinely always uses colons.)

    If you want to format it to hh:mm:ss tt, then you need to put that part in the ToString call:

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

    Or better yet (IMO) use "whatever the long time pattern is for the culture":

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

    Also note that hh is unusual; typically you don't want to 0-left-pad the number for numbers less than 10.

    (Also consider using my Noda Time API, which has a LocalTime type - a more appropriate match for just a "time of day".)

    0 讨论(0)
  • 2021-02-01 14:05

    The accepted solution doesn't cover edge cases. I found the way to do this with 4KB script. Handle your input and convert a data.

    Examples:

    00:00:00 -> 00:00:00
    12:01 -> 12:01:00
    12 -> 12:00:00
    25 -> 00:00:00
    12:60:60 -> 12:00:00
    1dg46 -> 14:06
    

    You got the idea... Check it https://github.com/alekspetrov/time-input-js

    0 讨论(0)
  • 2021-02-01 14:15
    string Time = "16:23:01";
    DateTime date = DateTime.Parse(Time, System.Globalization.CultureInfo.CurrentCulture);
    
    string t = date.ToString("HH:mm:ss tt");
    
    0 讨论(0)
提交回复
热议问题