开发者

Converting to Datetime issue

I am trying to convert this content into DateTime.

 DateTime dtmNextPayment = Convert.ToDateTime(DateTime.Now.AddMonths(1).Month.ToString() + "/" + DateTime.Now.Day.ToString() + "/" + DateTime.Now.AddYears(1).Year.ToString());
开发者_高级运维

Here, i get an exception "String was not recognized as a valid datetime". Where am i doing wrong?? Could some one help me. Thank you in advance..


There are a lot of issues here. First off, you never want to repeatedly use DateTime.Now like you are doing. Instead,

DateTime now = DateTime.Now;

and then use now. The reason you do this is because DateTime.Now could roll over to a new day, or month, or year between calls.

Of course, that doesn't fix your problem. Let's tackle that now. You are clearly trying to add one month to now, so why not

DateTime dtmNextPayment = now.AddMonths(1);

It is very important to note that now.AddMonths(1) does not mutate now; this is why you must assign it to a new instance of DateTime.

Next, the original version of your post had

DateTime dtmNextPayment = Convert.ToDateTime(DateTime.Now.AddMonths(1).Month.ToString() + "/" + DateTime.Now.Day.ToString() + "/" + DateTime.Now.Year.ToString());

When DateTime.Now is December 1, 2011, this will produce

new DateTime(2011, 1, 1);

which I doubt is what you intend. Do you see why?

Your attempt to edit this results in

new DateTime(2012, 2, 1)

when the date is January 1, 2011. I doubt that this what you intend as most businesses don't bill one month and one year in advance. Stop and think for a second, please.

Additionally, you will get an execption, for example, if the day is January 31, 2011 because there is no February 31, 2011 (or February 31, 2012) for that matter. This is why you are getting the exception that you are getting now. Run your code tomorrow (February 1, 2011), and it will be "fine".

Lastly, don't do what you are doing because there are serious culture issues. Not all cultures format dates the way that you are trying to format them.

Moral: DateTime has built-in methods that are already tested and avoid all of these damn issues. Use them. Any time you are trying to do logic on almost any object by converting parts of it to a string and then converting back you are invoking a seriously bad code smell.


Just do this:

DateTime dtmNextPayment = DateTime.Now.AddMonths(1);

no need to create a string to just parse it right back to a DateTime object.


Why dont you use: DateTime dtmNextPayment = DateTime.Now.AddMonths(1); ?


Try this one:

DateTime dtmNextPayment = DateTime.Now.AddDays(1).AddMonths(1).AddYears(1);

Here you get the current time and add to it a day and a month and a year.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜