Converting a String to DateTime

后端 未结 17 2607
南方客
南方客 2020-11-21 06:12

How do you convert a string such as 2009-05-08 14:40:52,531 into a DateTime?

17条回答
  •  囚心锁ツ
    2020-11-21 06:53

    DateTime.Parse

    Syntax:

    DateTime.Parse(String value)
    DateTime.Parse(String value, IFormatProvider provider)
    DateTime.Parse(String value, IFormatProvider provider, DateTypeStyles styles)
    

    Example:

    string value = "1 January 2019";
    CultureInfo provider = new CultureInfo("en-GB");
    DateTime.Parse(value, provider, DateTimeStyles.NoCurrentDateDefault););
    
    • Value: string representation of date and time.
    • Provider: object which provides culture specific info.
    • Styles: formatting options that customize string parsing for some date and time parsing methods. For instance, AllowWhiteSpaces is a value which helps to ignore all spaces present in string while it parse.

    It's also worth remembering DateTime is an object that is stored as number internally in the framework, Format only applies to it when you convert it back to string.

    • Parsing converting a string to the internal number type.

    • Formatting converting the internal numeric value to a readable string.

    I recently had an issue where I was trying to convert a DateTime to pass to Linq what I hadn't realised at the time was format is irrelevant when passing DateTime to a Linq Query.

    DateTime SearchDate = DateTime.Parse(searchDate);
    applicationsUsages = applicationsUsages.Where(x => DbFunctions.TruncateTime(x.dateApplicationSelected) == SearchDate.Date);
    

    Full DateTime Documentation

提交回复
热议问题