HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Normalizing `DateTime` values to strings

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
valuesnormalizingstringsdatetime

Problem

I have this as part of a project to normalize DateTime values to more readable strings, localized to the relative time in the past that they happened.

It allows you to make several customizations. If you don't want a time to show up, specify "" for the timeFormat, etc. You can change the reference DateTime so that you can measure values between any two DateTime points.

The idea is to put them in forms like:

Event happened just now

Event happened 29 minutes ago

Event happened yesterday at 3:54 pm

etc

I'm looking for any and all improvements (as per the standard rules).

I assume my use of optional statements is less than idea, but I'm open to any and all suggestions about everything here.

public static string ToNormalizedString(this DateTime DateTime, DateTime? reference = null, string dateFormat = "MMM d, yyyy", string timeFormat = "h:mm tt", string preDateString = "", string preTimeString = "at", bool capitalizeModifiers = true)
{
    string result = "";

    DateTime referenceDateTime = DateTime.UtcNow;

    if (reference.HasValue)
    {
        referenceDateTime = reference.Value;
    }

    if (DateTime.Date == referenceDateTime.Date)
    {
        TimeSpan TimeDifference = referenceDateTime - DateTime;

        if (TimeDifference  referenceDateTime.Date)
    {
        result = preDateString + DateTime.DayOfWeek.ToString() + (timeFormat == "" ? "" : " " + preTimeString + " " + DateTime.ToString(timeFormat));
    }
    else
    {
        result = preDateString + DateTime.ToString(dateFormat) + (timeFormat == "" ? "" : " " + preTimeString + " " + DateTime.ToString(timeFormat));
    }

    return result;
}


As usual this code is free to anyone who wishes to use it.

Solution

TimeSpan.FromMinutes(1) and TimeSpan.FromHours(1) are much easier to read than new TimeSpan(0, 1, 0) and new TimeSpan(1, 0, 0).

Consider using multiple return statements, instead of just the one.

Stick to the naming conventions: change the parameter DateTime to dateTime, and the variable TimeDifference to timeDifference.

It's a good idea to document that this is relative to UTC time, otherwise users might get strange behaviour like this:

var twoHoursAgo = DateTime.Now.AddHours(-2);
Console.WriteLine(twoHoursAgo.ToNormalizedString());


Just now

Code Snippets

var twoHoursAgo = DateTime.Now.AddHours(-2);
Console.WriteLine(twoHoursAgo.ToNormalizedString());

Context

StackExchange Code Review Q#107527, answer score: 6

Revisions (0)

No revisions yet.