System.ComponentModel.DateTimeOffsetConverter.ConvertTo C# (CSharp) Method

ConvertTo() public method

Converts the given value object to a object using the arguments.

public ConvertTo ( ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType ) : object
context ITypeDescriptorContext
culture CultureInfo
value object
destinationType System.Type
return object
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            // logic is exactly as in DateTimeConverter, only the offset pattern ' zzz' is added to the default
            // ConvertToString pattern.
            if (destinationType == typeof(string) && value is DateTimeOffset)
            {
                DateTimeOffset dto = (DateTimeOffset)value;
                if (dto == DateTimeOffset.MinValue)
                {
                    return string.Empty;
                }

                if (culture == null)
                {
                    culture = CultureInfo.CurrentCulture;
                }

                DateTimeFormatInfo formatInfo = null;
                formatInfo = (DateTimeFormatInfo)culture.GetFormat(typeof(DateTimeFormatInfo));

                string format;
                if (culture == CultureInfo.InvariantCulture)
                {
                    // note: the y/m/d format used when there is or isn't a time component is not consistent
                    // when the culture is invariant, because for some reason InvariantCulture's date format is
                    // MM/dd/yyyy. However, this matches the behavior of DateTimeConverter so it is preserved here.

                    if (dto.TimeOfDay.TotalSeconds == 0)
                    {
                        // pattern just like DateTimeConverter when DateTime.TimeOfDay.TotalSeconds==0
                        // but with ' zzz' offset pattern added.
                        return dto.ToString("yyyy-MM-dd zzz", culture);
                    }
                    else
                    {
                        return dto.ToString(culture);
                    }
                }
                if (dto.TimeOfDay.TotalSeconds == 0)
                {
                    // pattern just like DateTimeConverter when DateTime.TimeOfDay.TotalSeconds==0
                    // but with ' zzz' offset pattern added.
                    format = formatInfo.ShortDatePattern + " zzz";
                }
                else
                {
                    // pattern just like DateTimeConverter when DateTime.TimeOfDay.TotalSeconds!=0
                    // but with ' zzz' offset pattern added.
                    format = formatInfo.ShortDatePattern + " " + formatInfo.ShortTimePattern + " zzz";
                }

                return dto.ToString(format, CultureInfo.CurrentCulture);
            }

            return base.ConvertTo(context, culture, value, destinationType);
        }
    }