Ejemplo n.º 1
0
        /// <summary>
        /// Converts the given object to the type of this converter, using the specified context and culture information.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Object"/> that represents the converted value.
        /// </returns>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context. </param>
        /// <param name="culture">The <see cref="T:System.Globalization.CultureInfo"/> to use as the current culture. </param>
        /// <param name="value">The <see cref="T:System.Object"/> to convert. </param>
        /// <exception cref="T:System.NotSupportedException">The conversion cannot be performed. </exception>
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            string @string = value as string;

            if (@string != null)
            {
                Instant instant;
                if (TimeHelpers.GetInstantPatterns(culture).TryParseAny(@string.Trim(), out instant))
                {
                    return(instant);
                }

                DateTimeOffset dateTimeOffset;
                if (DateTimeOffset.TryParse(@string, out dateTimeOffset))
                {
                    return(Instant.FromDateTimeOffset(dateTimeOffset));
                }

                throw new NotSupportedException(
                          // ReSharper disable once AssignNullToNotNullAttribute
                          string.Format(Resources.InstantConverter_ConvertFrom_CannotParse, @string));
            }
            if (value is DateTime)
            {
                DateTime dateTime = (DateTime)value;
                return(Instant.FromDateTimeUtc(dateTime.ToUniversalTime()));
            }
            if (value is DateTimeOffset)
            {
                DateTimeOffset dateTimeOffset = (DateTimeOffset)value;
                return(Instant.FromDateTimeOffset(dateTimeOffset));
            }
            if (value is OffsetDateTime)
            {
                OffsetDateTime offsetDateTime = (OffsetDateTime)value;
                return(offsetDateTime.ToInstant());
            }
            if (value is ZonedDateTime)
            {
                ZonedDateTime zonedDateTime = (ZonedDateTime)value;
                return(zonedDateTime.ToInstant());
            }

            return(base.ConvertFrom(context, culture, value));
        }