Zan
Zan

Reputation: 114

Determining whether the new date is the default new DateTime() or not

Here is my question:

DateTime previousDate = new DateTime();
DateTime currentDate = new DateTime();
foreach (ApproverVo approver in approvers)
{
    if (previousDate != null)
    {
        currentDate = (DateTime)approver.ApprovalDate;
        totalTimeSpan += (currentDate - previousDate).TotalDays;
        previousDate = currentDate;
    } else
        previousDate = (DateTime)approver.ApprovalDate;
}

When the previous date is declared in the beginning, it contains the default value of DateTime(). What I want to do is to find out whether the previousDate has been assigned with proper date or not.

Advice please, thanks

Upvotes: 4

Views: 150

Answers (2)

MikeM
MikeM

Reputation: 27405

check if previousDate == DateTime.MinValue since

DateTime previousDate = new DateTime();

is equivalent to

DateTime previousDate = DateTime.MinValue;

from MSDN DateTime Structure documentation:

DateTime dat1 = new DateTime();
// The following method call displays 1/1/0001 12:00:00 AM.
Console.WriteLine(dat1.ToString(System.Globalization.CultureInfo.InvariantCulture));
// The following method call displays True.
Console.WriteLine(dat1.Equals(DateTime.MinValue));

Upvotes: 2

Iswanto San
Iswanto San

Reputation: 18569

Assume your approval date doesn't have value equals DateTime.MinValue :

DateTime previousDate = DateTime.MinValue;
DateTime currentDate = new DateTime();
foreach (ApproverVo approver in approvers)
{
    if (previousDate != DateTime.MinValue)
    {
        currentDate = (DateTime)approver.ApprovalDate;
        totalTimeSpan += (currentDate - previousDate).TotalDays;
        previousDate = currentDate;
    } else
        previousDate = (DateTime)approver.ApprovalDate;
}

UPDATE

According @mdmullinax answers, above code is similar with :

DateTime previousDate = new DateTime();
DateTime currentDate = new DateTime();
foreach (ApproverVo approver in approvers)
{
    if (previousDate != new DateTime())
    {
        currentDate = (DateTime)approver.ApprovalDate;
        totalTimeSpan += (currentDate - previousDate).TotalDays;
        previousDate = currentDate;
    } else
        previousDate = (DateTime)approver.ApprovalDate;
}

Upvotes: 2

Related Questions