Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

winforms - C#: how do I subtract two dates?

Here's my code:

DateTime date1 = new DateTime(byear, bmonth, bday, 0, 0, 0);
DateTime datenow =  DateTime.Now;
DateTime date2 = datenow - date1

On the last line I am getting this error:

Error 1 Cannot implicitly convert type 'System.TimeSpan' to 'System.DateTime'

How do I subtract two dates?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well the point is that if you think of it, subtracting a date to another should not yield a date, it should yield a time span. And that is what happens when you use DateTime.Subtract().

TimeSpan timeSpan = datenow - date1; //timespan between `datenow` and `date1`

This will make your current code work.

If on the other hand you want to subtract, let's say, one year from your date, you can use:

DateTime oneYearBefore = DateTime.Now.AddYears(-1); //that is, subtracts one year

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...