开发者

C#: how do I subtract two dates?

开发者 https://www.devze.com 2022-12-27 03:30 出处:网络
Here\'s my code: DateTime date1 = new DateTime(byear, bmonth, bday, 0, 0, 0); DateTime datenow =DateTime.Now;

Here's my code:

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

On the las开发者_StackOverflow中文版t line I am getting this error:

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

How do I subtract two dates?


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


As already mentioned, date - date gives you a TimeSpan, not a DateTime. If you want a DateTime, use AddDays(-1) as in:

DateTime subtractedDate = date1.AddDays(-1); 


The result of a date comparison is a TimeSpan, not a DateTime value.

You want to do this:

TimeSpan result = datenow - date1;


.Subtract has two overloads. One accepts a DateTime and returns a TimeSpan, the other accepts a TimeSpan and returns a DateTime.

In other words, if you subtract a date from a date, you get the timespan difference. Otherwise, if you subtract a timespan from a date, you get a new date.


Can you clarify what you are trying calculate? The difference between any two dates in C# or real life is a time span. If you are trying to calculate age then what you want is the timespan since their birth. Change Date2 to to

Timespan age = datenow - date1;


You are correctly subtracting two dates in your code. What's going on is that you expect the difference between the two dates to be another date, and that's not the case.

As other posters have noticed, you get a TimeSpan. From your variable names I get the sense you're trying to find out someone's age.

Age is not a date, it's a duration. Read up on the TimeSpan object and you will find that it correctly expresses the idea you are looking for.

I'm not 0029-01-01 years old, I'm 29 years old. (Today is not my birthday, but assume it is for easy math.)

If you're trying to show someone's age in a control and that control wants a DateTime you are probably using the wrong control to do it.


Try using ticks...?

DateTime date1 = new DateTime(1986, 3, 16, 0, 0, 0);
DateTime datenow =  DateTime.Now;
DateTime date2 = new DateTime(datenow.Subtract(date1).Ticks);


You are expecting the difference of two dates to be a date which is not. That being said, if you need to subtract a certain number of days or months, it can easily be done using the built in methods of the DateTime object such as .AddDays(-1), note that I used a negative number to substract, you can apply the opposite. Here is a quick example.

        DateTime now = DateTime.Now;

        // Get the date 7 days ago
        DateTime sevenDaysAgo = now.AddDays(-7);

        // Bulk: Get the date 7 days and two hours ago
        DateTime sevenDaysAndtwoHoursAgo = now.Add(-(new TimeSpan(7, 2, 0, 0)));


Use this code:

DateTime? Startdate = cStartDate.GetValue<DateTime>().Date;
DateTime? Enddate = cEndDate.GetValue<DateTime>().Date;
TimeSpan diff =  Enddate.GetValue<DateTime>()- Startdate.GetValue<DateTime>() ;
txtDayNo.Text = diff.Days.GetValue<string>();


TimeSpan Example:

private void Form1_Load(object sender, EventArgs e)
    {
        DateTime startdatetime = new DateTime(2001, 1, 2, 14, 30, 0);
        DateTime enddatetime = DateTime.Now;
        TimeSpan difference = enddatetime.Subtract(startdatetime);


        string sdifference = "TotalDays:" + difference.TotalDays + Environment.NewLine;
        sdifference += "TotalHours:" + difference.TotalHours + Environment.NewLine;
        sdifference += "TotalMilliseconds:" + difference.TotalMilliseconds + Environment.NewLine;
        sdifference += "TotalMinutes:" + difference.TotalMinutes + Environment.NewLine;
        sdifference += "TotalSeconds:" + difference.TotalSeconds + Environment.NewLine;
        sdifference += "Ticks:" + difference.Ticks + Environment.NewLine;            
        sdifference += "Total:" + difference.Days + " days, " + difference.Hours + " hours, " + difference.Minutes + " minutes, " + difference.Seconds + " seconds and " + difference.Milliseconds + " milliseconds.";

        TextBox TextBox1 = new TextBox();
        TextBox1.Multiline = true;
        TextBox1.Dock = DockStyle.Fill;
        TextBox1.Text = sdifference;
        this.Controls.Add(TextBox1);

    }


Not exactly an answer to your question, but I prefer using var instead of annotating the variables with types. var IMO makes code look much cleaner than otherwise.

Here's your code snippet with vars:

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

EDIT:

For the C# developers with the var-is-bad mindset:

[ Original Post Here ]

I use var extensively. There has been criticism that this diminishes the readability of the code, but no argument to support that claim.

Admittedly, it may mean that it's not clear what type we are dealing with. So what? This is actually the point of a decoupled design. When dealing with interfaces, you are emphatically not interested in the type a variable has. var takes this much further, true, but I think that the argument remains the same from a readability point of view: The programmer shouldn't actually be interested in the type of the variable but rather in what a variable does. This is why Microsoft also calls type inference “duck typing.”

So, what does a variable do when I declare it using var? Easy, it does whatever IntelliSense tells me it does. Any reasoning about C# that ignores the IDE falls short of reality. In practice, every C# code is programmed in an IDE that supports IntelliSense.

If I am using a var declared variable and get confused what the variable is there for, there's something fundamentally wrong with my code. var is not the cause, it only makes the symptoms visible. Don't blame the messenger.

Now, the C# team has released a coding guideline stating that var should only be used to capture the result of a LINQ statement that creates an anonymous type (because here, we have no real alternative to var). Well, screw that. As long as the C# team doesn't give me a sound argument for this guideline, I am going to ignore it because in my professional and personal opinion, it's pure baloney. (Sorry; I've got no link to the guideline in question.)

Actually, there are some (superficially) good explanations on why you shouldn't use var but I still believe they are largely wrong. Take the example of “searchabililty”: the author claims that var makes it hard to search for places where MyType is used. Right. So do interfaces. Actually, why would I want to know where the class is used? I might be more interested in where it is instantiated and this will still be searchable because somewhere its constructor has to be invoked (even if this is done indirectly, the type name has to be mentioned somewhere). - Konrad Rudolph

0

精彩评论

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