开发者

Why am I unable to convert Datetime to the required format

开发者 https://www.devze.com 2023-02-11 20:50 出处:网络
This is the requirement I am having my field declared in my class file as Datetime. I am taking a string and i wou开发者_如何学Gold like to convert it to Datetime as my filed in my class is in date

This is the requirement

I am having my field declared in my class file as Datetime.

I am taking a string and i wou开发者_如何学Gold like to convert it to Datetime as my filed in my class is in date time

I always pass it as

    String date="9999-12-31 00:00:00"

I would like to convert this to date time so that the output format should be the same as the given string


Quite simply, you're trying to parse "9999-12-31" with a format string of "yyyy-MM-ddTHH:mm:ss" - which it doesn't comply to, as it has no time.

EDIT: Okay, so you've now changed the input to "9999-12-31 21:34 PM" which still isn't in the appropriate format - there's no T, no seconds, and there's an am/pm designator. Why are you not using a format string which actually matches your input?

But if "9999-12-31" is the input, what output are you expecting?


Just change

DateTime dt = DateTime.ParseExact(strDate, "yyyy-MM-ddTHH:mm:ss", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None);

to

DateTime dt = DateTime.Parse(strDate, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None);

This will convert 9999-12-31 21:34 PM to 9999-12-31 (if using dt.ToString("yyy-MM-dd")).

Note that this DateTime will contain the hours/minutes etc. If you want to remove the hours/minutes from the DateTime, use something like this:

 dt = new DateTime(dt.Year, dt.Month, dt.Day, 0, 0, 0, dt.Kind);

If you specify an format to DateTime.ParseExact, then your input string has to have exactly this format to be convertet to a DateTime. You can use DateTime.Parse instead.


DateTime dt = DateTime.Parse(strDate, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None);


DateTime.ParseExact(
    strDate, 
    "yyyy-MM-dd hh:mm tt", 
    DateTimeFormatInfo.InvariantInfo, 
    DateTimeStyles.None);
0

精彩评论

暂无评论...
验证码 换一张
取 消