How do you parse a time string with unit (us, ms, s, etc.) to TimeSpan

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • alexandreperr

    #1

    How do you parse a time string with unit (us, ms, s, etc.) to TimeSpan

    Hi folks,

    I am willing to create a TypeConverter that allows converting a string in a TimeSpan.
    The thing is I want to be able to enter a time with units such as:
    75ms or m
    125us or u
    0.25s

    I don't really know what to use for parsing the string.
    I would like to use RegEx but I can't figure what format to use.

    So far I have this structure of Converter:

    Code:
    	public class TimeConverter : TypeConverter
    	{
    
    		public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    		{
    			if (sourceType == typeof(string))
    				return true;
    			return base.CanConvertFrom(context, sourceType);
    		}
    
    		public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    		{
    			if (destinationType == typeof(InstanceDescriptor))
    				return true;
    			return base.CanConvertTo(context, destinationType);
    		}
    
    		public override object ConvertFrom(ITypeDescriptorContext context,
    			System.Globalization.CultureInfo culture, object value)
    		{
    			if (value is string)
    			{
    				string str = ((string)value);
    				TimeSpan ts;
    
    				ts = TimeSpan.Parse(str);
    
    				return ts;
    			}
    			return base.ConvertFrom(context, culture, value);
    		}
    
    		// Overrides the ConvertTo method of TypeConverter.
    		public override object ConvertTo(ITypeDescriptorContext context,
    		   System.Globalization.CultureInfo culture, object value, Type destinationType)
    		{
    			return base.ConvertTo(context, culture, value, destinationType);
    		}
    	}
    Thanks for your help.

    Alex
  • Christian Binder
    Recognized Expert New Member
    • Jan 2008
    • 218

    #2
    I think, the simplest way would be if the last character are m, s, u ms or us.
    And if its one of these check the previous string (without time-unit) if it's a number.
    I don't know much about RegEx, so I would do it this way.
    E.g.
    Code:
    string timestr = 125us;
    double timevalue;
    if(timestr.EndsWith("us") && double.TryParse(timestr.Substring(0, timestr.Length - 2), out timevalue)) {
      //create timespan
    } else if(timestr.EndsWiths("s") && double.TryParse(timestr.Substring(0, timestr.Length - 1), out timevalue)) {
      //create timespan
    }
    else if //...

    Comment

    Working...