Category Archives: datetime

Calculate age (for instance, on reference data)

Now and then, I have to calculate ages (for instance, on a reference date). The method to calculate ages in .NET is pretty simple, although it can be ‘a pain in the ass’ to find out how simple it should have been :) … Enjoy the code :) !

public static class DateTimeHelper
{
    public static int CalculateAge(DateTime birthday)
    {
        return CalculateAge(DateTime.Now, birthday);
    }

    public static int CalculateAge(DateTime referenceDate, DateTime birthday)
    {
        // calculate age in years on the given reference date.
        var comparisonDate = new DateTime(birthday.Year, referenceDate.Month, referenceDate.Day);

        return (comparisonDate.Date < birthday.Date)
                      ? referenceDate.Year - birthday.Year - 1
                      : referenceDate.Year - birthday.Year;
    }
}

Logging duration with System.Diagnostics.StopWatch instead of using DateTime.Now

Still using two DateTime.Now calls to determine the duration of a certain call execution, like beneath?

DateTime start = DateTime.Now;
DoSomeCall();
double secondsToLog = (DateTime.Now - start).TotalSeconds;

This is not at all necessary: using the StopWatch class. The StopWatch class is more efficient than any other solution provided or created in .NET since it uses low-level API calls and supports a high-resolution performance counter (when there is hardware and software support).

Stopwatch watch = new Stopwatch();
watch.Start();
DoSomeCall();
watch.Stop();
double secondsToLog = watch.Elapsed.TotalSeconds;

IsDateTime in .NET for both ticks and string representation

Some while ago I developed a Settings system, where the SettingValue type should be checked. The DateTime.TryParse function did not do all the work I wanted it to do, so I thought ‘why not develop my own workaround’ :) ? It is posted below…

/// <summary>
/// The IsDateTime function returns whether the given expression is a DateTime or not.
/// </summary>
/// <param name="expression">Expression to check for being DateTime.</param>
/// <returns>Boolean</returns>
/// <remarks>
/// The DateTime expression can be given as ticks or as normal DateTime representation.
/// </remarks>
public static bool IsDateTime(object expression) {
if(expression == null) return false;Bert Loedeman

string stringExpression = System.Convert.ToString(expression);
if(String.IsNullOrEmpty(stringExpression)) return false;

// DateTime can be specified in ticks. In that case the string should be convertible
// to a long (System.Int64) and fit in a specific range.
long retLong;
if(Int64.TryParse(stringExpression, out retLong)) {
// Ticks: 0 = DateTime.MinValue, 0x2bca2875f4373fff = DateTime.MaxValue
if((retLong < DateTime.MinValue.Ticks) || (retLong > DateTime.MaxValue.Ticks)) return false;
return true;
}

DateTime retDateTime;
return DateTime.TryParse(stringExpression, out retDateTime);
}