Created
October 27, 2017 08:26
-
-
Save mollyporph/7a0631c23720b989e0c1ab595d46b471 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Text.RegularExpressions; | |
public class Program | |
{ | |
public static Regex dateRegex = new Regex(@"(\d+)([smhd])",RegexOptions.Compiled | RegexOptions.IgnoreCase); | |
public static void Main() | |
{ | |
Console.WriteLine(DateTime.Now.Add(TS("1d"))); | |
Console.WriteLine(DateTime.Now.Add(TS("1h"))); | |
Console.WriteLine(DateTime.Now.Add(TS("24h"))); | |
Console.WriteLine(DateTime.Now.Add(TS("90m"))); | |
} | |
public static TimeSpan TS(string _dateString) | |
{ | |
var match = dateRegex.Match(_dateString); | |
if(!match.Success) | |
throw new ArgumentException("failed to parse"); | |
var part = match.Groups[2].Value.ToLower(); | |
var val = match.Groups[1]; | |
switch(part) | |
{ | |
case "s": | |
return TimeSpan.FromSeconds(int.Parse(val.Value)); | |
case "m": | |
return TimeSpan.FromMinutes(int.Parse(val.Value)); | |
case "h": | |
return TimeSpan.FromHours(int.Parse(val.Value)); | |
case "d": | |
return TimeSpan.FromDays(int.Parse(val.Value)); | |
default: | |
throw new ArgumentException("failed to parse"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment