Converting a relative date string to a DateTime object

I have a relative line datetimelike:

  • "5 minutes ago"
  • 10 hours ago
  • 3 days ago, etc.

How can I convert this to exact datetime, as the exact opposite of this question

+5
source share
3 answers

This code should work:

        string input = "10 days ago";

        DateTime result = DateTime.MinValue;
        int minutesMultiplier = 0;

        if (input.Contains("minute"))
            minutesMultiplier = 1;
        else
            if (input.Contains("hour"))
                minutesMultiplier = 60;
            else
                if (input.Contains("day"))
                    minutesMultiplier = 1440;
                else
                    throw new Exception("Couldn't parse time format");

        string numberStr = input.Split(' ')[0];
        int number;
        if (int.TryParse(numberStr, out number))
            result = DateTime.Now.AddMinutes(-number * minutesMultiplier);

It analyzes the name of the interval (for example, minute, hour, day) and multiplies them by the number of minutes, because later it uses the method DateTime.Now.AddMinutes, the same can be done with a TimeSpancall DateTime.Now.Add.

, , , "10 15 ":

        // If there are mixed interval types in an input string
        string input = "10 days and 10 hours ago";

        // Parse out the intervals and numbers
        var matches = Regex.Matches(input, 
                       @"(?<number>\d+)\s(?<interval>(day)|(minute)|(hour))");

        // Convert them to dictionary
        var dic = matches
            .Cast<Match>()
            .ToDictionary(
                key => key.Groups["interval"].Value, 
                o => int.Parse(o.Groups["number"].Value));

        // Calculate the total number of minutes for each interval
        DateTime result = DateTime.MinValue;
        int totalMinutes = 0;

        foreach (var keyValue in dic)
        {
             if (keyValue.Key.Contains("minute"))
                 totalMinutes += keyValue.Value;
            else
                 if (keyValue.Key.Contains("hour"))
                    totalMinutes += keyValue.Value * 60;
                else
                     if (keyValue.Key.Contains("day"))
                        totalMinutes += keyValue.Value * 1440;
                    else
                        throw new Exception("Unparsable time format");
        }

        result = DateTime.Now.AddMinutes(-totalMinutes);
+6

, , , .

, , (.. , , ..), , ( ago from).

, TimeSpan DateTime.Now, .

, , .

+6

TimeSpan DateTime.Now ( DateTime ).

You can use methods such as int.Parseto convert numbers (number of minutes, hours, etc.) to an integer value and copy them to your value TimeSpan. The exact parsing algorithm depends on the actual format of your lines, that is, which words are allowed there and in what order the numbers can be displayed.

If the lines are already selected, as shown in your question, you can try and parse them using a regex (with Regexclass ):

^(\d+)\s+([a-z]+)\s+ago$
+2
source

All Articles