Parse C# string to DateTime

后端 未结 3 873
暗喜
暗喜 2020-11-29 10:13

I have a string like this: 250920111414

I want to create a DateTime object from that string. As of now, I use substring and do it like this:

string d         


        
相关标签:
3条回答
  • 2020-11-29 10:43
    string iDate = "05/05/2005";
    DateTime oDate = Convert.ToDateTime(iDate);
    DateTime oDate = DateTime.ParseExact(iString, "yyyy-MM-dd HH:mm tt",null);
    
    
    

    DateTime Formats

    0 讨论(0)
  • 2020-11-29 10:50

    You could use:

    DateTime dt = DateTime.ParseExact(
                      date, 
                      "ddMMyyyyHHmm",
                      CultureInfo.InvariantCulture);
    
    0 讨论(0)
  • 2020-11-29 10:58

    Absolutely. Guessing the format from your string, you can use ParseExact

    string format = "ddMMyyyyHHmm";
    
    DateTime dt = DateTime.ParseExact(value, format, CultureInfo.InvariantCulture);
    

    or TryParseExact:

    DateTime dt;
    bool success = DateTime.TryParseExact(value, format, 
                         CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
    

    The latter call will simply return false on parse failure, instead of throwing an exception - if you may have bad data which shouldn't cause the overall task to fail (e.g. it's user input, and you just want to prompt them) then this is a better call to use.

    EDIT: For more details about the format string details, see "Custom Date and Time Format Strings" in MSDN.

    0 讨论(0)
提交回复
热议问题