TimeSpanConverter.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //
  2. // System.ComponentModel.TimeSpanConverter
  3. //
  4. // Authors:
  5. // Martin Willemoes Hansen ([email protected])
  6. // Andreas Nahr ([email protected])
  7. //
  8. // (C) 2003 Martin Willemoes Hansen
  9. // (C) 2003 Andreas Nahr
  10. //
  11. using System.Globalization;
  12. namespace System.ComponentModel
  13. {
  14. public class TimeSpanConverter : TypeConverter
  15. {
  16. public TimeSpanConverter()
  17. {
  18. }
  19. public override bool CanConvertFrom (ITypeDescriptorContext context, Type sourceType)
  20. {
  21. if (sourceType == typeof (string))
  22. return true;
  23. return base.CanConvertFrom (context, sourceType);
  24. }
  25. public override bool CanConvertTo (ITypeDescriptorContext context, Type destinationType)
  26. {
  27. if (destinationType == typeof (string))
  28. return true;
  29. return base.CanConvertTo (context, destinationType);
  30. }
  31. public override object ConvertFrom (ITypeDescriptorContext context, CultureInfo culture, object value)
  32. {
  33. if (value.GetType() == typeof (string)) {
  34. string TimeSpanString = (string) value;
  35. try {
  36. // LAMESPEC Doc says TimeSpan uses Ticks, but MS uses time format:
  37. // [ws][-][d.]hh:mm:ss[.ff][ws]
  38. return TimeSpan.Parse (TimeSpanString);
  39. } catch {
  40. throw new FormatException (TimeSpanString + "is not valid for a TimeSpan.");
  41. }
  42. }
  43. return base.ConvertFrom (context, culture, value);
  44. }
  45. public override object ConvertTo (ITypeDescriptorContext context, CultureInfo culture, object value,
  46. Type destinationType)
  47. {
  48. if (destinationType == typeof (string) && value != null && value.GetType() == typeof (TimeSpan)) {
  49. // LAMESPEC Doc says TimeSpan uses Ticks, but MS uses time format
  50. // [ws][-][d.]hh:mm:ss[.ff][ws]
  51. return ((TimeSpan) value).ToString();
  52. }
  53. return base.ConvertTo (context, culture, value, destinationType);
  54. }
  55. }
  56. }