DateTimeConverter.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. //
  2. // System.ComponentModel.DateTimeConverter
  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 DateTimeConverter : TypeConverter
  15. {
  16. public DateTimeConverter()
  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 DateString = (String) value;
  35. try {
  36. if (culture == null)
  37. // try to parse string
  38. return DateTime.Parse (DateString);
  39. else
  40. // try to parse string
  41. return DateTime.Parse (DateString, culture.DateTimeFormat);
  42. } catch {
  43. throw new FormatException (DateString + "is not a valid DateTime value.");
  44. }
  45. }
  46. return base.ConvertFrom (context, culture, value);
  47. }
  48. public override object ConvertTo (ITypeDescriptorContext context, CultureInfo culture, object value,
  49. Type destinationType)
  50. {
  51. if (destinationType == typeof (string) && value != null && (value is DateTime)) {
  52. CultureInfo CurrentCulture = culture;
  53. if (CurrentCulture == null)
  54. CurrentCulture = CultureInfo.CurrentCulture;
  55. DateTime ConvertTime = (DateTime) value;
  56. if (CurrentCulture.Equals(CultureInfo.InvariantCulture)) {
  57. if (ConvertTime.Equals(ConvertTime.Date))
  58. return ConvertTime.ToString("yyyy-mm-dd");
  59. else
  60. return ConvertTime.ToString ();
  61. } else {
  62. if (ConvertTime.Equals(ConvertTime.Date))
  63. return ConvertTime.ToString (CurrentCulture.DateTimeFormat.ShortDatePattern);
  64. else
  65. return ConvertTime.ToString (CurrentCulture.DateTimeFormat.ShortDatePattern +
  66. " " + CurrentCulture.DateTimeFormat.ShortTimePattern);
  67. }
  68. }
  69. return base.ConvertTo (context, culture, value, destinationType);
  70. }
  71. }
  72. }