I am having relative datetime
string like:
How can I convert this to exact datetime
, as exactly opposite of this question
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With