Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert relative datetime string into DateTime object

I am having relative datetime string like:

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

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

like image 868
Agent007 Avatar asked Aug 17 '12 09:08

Agent007


People also ask

How do I convert a string to a datetime in Python?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.

How do I convert a string to datetime in Timedelta?

Method 1: Program to convert string to DateTime using datetime. strptime() function. strptime() is available in DateTime and time modules and is used for Date-Time Conversion. This function changes the given string of datetime into the desired format.

How do you convert a string to a date in JavaScript?

Just concatenate your date string (using ISO format) with "T00:00:00" in the end and use the JavaScript Date() constructor, like the example below. const dateString = '2014-04-03' var mydate = new Date(dateString + "T00:00:00"); console.


1 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 does the parsing of an interval name (such as minute, hour, day) and multiplies them to get the number of minutes because later on it uses DateTime.Now.AddMinutes method, same thing could be done using TimeSpan and calling DateTime.Now.Add.

Here is one more example that handles case of a string that contains more than one interval name, such as "10 hours and 15 minutes ago":

        // 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);
like image 100
Ivan Golović Avatar answered Sep 28 '22 01:09

Ivan Golović