C#: how do I subtract two dates?

后端 未结 11 795
死守一世寂寞
死守一世寂寞 2020-12-19 06:52

Here\'s my code:

DateTime date1 = new DateTime(byear, bmonth, bday, 0, 0, 0);
DateTime datenow =  DateTime.Now;
DateTime date2 = datenow - date1
11条回答
  •  执笔经年
    2020-12-19 07:31

    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

提交回复
热议问题