Convert string to Datetime dd/MM/yyyy hh:mm:ss tt

前端 未结 4 960
悲哀的现实
悲哀的现实 2021-01-03 05:52

How can I convert this 7/3/2015 12:40:02 PM to DateTime with format \"dd/MM/yyyy hh:mm:ss tt\" I have done like this:

BreackEndTime         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-03 06:31

    Since months and days can have a single digit use

    BreackEndTime = DateTime.ParseExact(configViewModel.EndPause, "d/M/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
    

    The "M" Custom Format Specifier (exemplary, d works similar)

    The "M" custom format specifier represents the month as a number from 1 through 12 (or from 1 through 13 for calendars that have 13 months). A single-digit month is formatted without a leading zero.

    Update

    Since the hour can also have a single digit you have to use:

    DateTime.ParseExact("7/3/2015 1:52:16 PM", "d/M/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);` 
    

    ... so "d/M/yyyy h:mm:ss tt" instead of "d/M/yyyy hh:mm:ss tt". Note that the same applies to the minutes and seconds, if they also can have single digits use "d/M/yyyy h:m:s tt". I hope you got the point now.

提交回复
热议问题