Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...