예제 #1
0
 private void InitializeMembers()
 {
     this.encoding = null;
     this.culture = null;
     this.numberStyle = NumberStyles.Float;
     this.dateTimeStyle = DateTimeStyles.None;
 }
예제 #2
0
        public static DateTime ParseExact(string s, string format, IFormatProvider provider, DateTimeStyles style)
        {
            // Note: the Date/Time handling in java is just broken, and putting a 
            //       .NET compatibility layer on top of it will probalby not fix much
            if (s == null || format == null)
                throw new ArgumentNullException();

            if ((style & DateTimeStyles.AllowLeadingWhite) != 0)
                s = s.TrimStart();
            if ((style & DateTimeStyles.AllowTrailingWhite) != 0)
                s = s.TrimEnd();
            if ((style & DateTimeStyles.AllowWhiteSpaces) != 0)
                s = s.Trim();

            try
            {
                var formatter = DateFormatFactory.GetFormat(format, DateTimeKind.Unspecified, provider);
                formatter.Format.TimeZone = TimeZone.GetTimeZone("UTC"); // reset mutable value

                Date parsed = formatter.Format.Parse(s);

                var result = FromParsedDate(parsed, s, style, formatter.Format, formatter.ContainsK, formatter.UseUtc);
                return result;
            }
            catch (ArgumentException ex)
            {
                throw new FormatException(ex.Message);
            }
            catch (ParseException ex)
            {
                throw new ArgumentException(ex.Message, "s");
            }
        }
예제 #3
0
        public DateParser(string format, DateTimeKind kind)
        {
            switch (kind)
            {
                case DateTimeKind.Local:
                    _style = DateTimeStyles.AssumeLocal;
                    break;

                case DateTimeKind.Utc:
                    _style = DateTimeStyles.AssumeUniversal;
                    break;

                default:
                    throw new ArgumentOutOfRangeException("kind");
            }

            switch (format)
            {
                case "ABSOLUTE":
                    break;

                case "ISO8601":
                    break;

                case "DATE":
                    break;
            }
        }
예제 #4
0
        /// <summary>
        /// Convert string date to datetime
        /// </summary>
        /// <param name="strValue">string to convert</param>
        /// <param name="defaultValue">default value when invalid date</param>
        /// <param name="culture">date culture</param>
        /// <param name="dateTimeStyle">datetime style</param>
        /// <returns>datetime</returns>
        public static DateTime TryParseDate(this string strValue, DateTime defaultValue, CultureInfo culture, DateTimeStyles dateTimeStyle)
        {
            DateTime date;
            if (DateTime.TryParse(strValue, culture, dateTimeStyle, out date))
                return date;

            #region FromOADate
            if (strValue.IsValidDouble(NumberStyles.Float, culture))
            {
                var doubleValue = strValue.TryParseDouble(-99);
                if (doubleValue >= -657434.999 && doubleValue <= 2593589)
                {
                    try
                    {
                        return DateTime.FromOADate(doubleValue);
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e);
                    }
                }
            } 
            #endregion
            
            return defaultValue;
        }
 /// <summary>
 /// Configures <see cref="GlobalizationConfiguration"/>
 /// </summary>
 /// <param name="environment">An <see cref="INancyEnvironment"/> that should be configured.</param>
 /// <param name="supportedCultureNames">Cultures that the application can accept</param>
 /// <param name="defaultCulture">Used to set a default culture for the application</param>
 /// <param name="dateTimeStyles">The <see cref="DateTimeStyles"/> that should be used for date parsing.</param>
 /// <remarks>If defaultCulture not specified the first supported culture is used</remarks>
 public static void Globalization(this INancyEnvironment environment, IEnumerable<string> supportedCultureNames, string defaultCulture = null, DateTimeStyles? dateTimeStyles = null)
 {
     environment.AddValue(new GlobalizationConfiguration(
         supportedCultureNames: supportedCultureNames,
         defaultCulture: defaultCulture,
         dateTimeStyles: dateTimeStyles));
 }
예제 #6
0
        internal static readonly long TicksAt1970 = 621355968000000000L; //new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;

        /// <summary>
        /// Parses string in following formats to DateTime representation:
        ///  - @decimal@ - 1970-01-01 + decimal (millisec) - UTC!
        ///  - \/Date(decimal)\/ - 1970-01-01 + decimal (millisec) - UTC!
        ///  - \/Date(yyyy,MM,dd[,hh,mm,ss,mmm])\/ - direct params - UTC!
        ///  - decimal - 1970-01-01 + decimal (millisec/sec) - UTC!
        ///  - ISO format - with time zones support
        /// </summary>
        public static DateTime ParseDateTime(string text, IFormatProvider provider, DateTimeStyles styles, JSonDateTimeKind kind)
        {
            if (!String.IsNullOrEmpty(text))
            {
                var date = text.Replace(" ", String.Empty).Replace("\t", String.Empty);

                if (date.Length > 2)
                {
                    if (date[0] == '@' && date[date.Length - 1] == '@')
                        return ParseDateTimeAsDecimal(date.Substring(1, date.Length - 2));

                    if (date.StartsWith("\\/Date(", StringComparison.OrdinalIgnoreCase) && date.EndsWith(")\\/"))
                        return ParseDateTimeAsArrayOfDecimals(date.Substring(7, date.Length - 10));

                    if (date.StartsWith("/Date(", StringComparison.OrdinalIgnoreCase) && date.EndsWith(")/"))
                        return ParseDateTimeAsArrayOfDecimals(date.Substring(6, date.Length - 8));
                }
            }

            // try to parse date as a pure number:
            long dateValue;
            if (NumericHelper.TryParseInt64(text, out dateValue))
                return ToDateTime(dateValue, kind);

            // always try to parse as ISO format, to get the result or throw a standard exception, when non-matching format given:
            return DateTime.Parse(text, provider, styles);
        }
        public static DateTimeOffset? DateTimeOffsetTryParseNullable(string value, IFormatProvider provider, DateTimeStyles styles)
        {
            DateTimeOffset result;
            if (!DateTimeOffset.TryParse(value, provider, styles, out result))
                return null;

            return result;
        }
        /// <summary>
        /// Deserialize an object
        /// </summary>
        /// <param name="value">The object to deserialize</param>
        /// <param name="type">The type of object to deserialize</param>
        /// <param name="dateTimeStyles">The <see cref="DateTimeStyles"/> ton convert <see cref="DateTime"/> objects</param>
        /// <returns>A instance of <paramref name="type" /> deserialized from <paramref name="value"/></returns>
        public override object DeserializeObject(object value, Type type, DateTimeStyles dateTimeStyles)
        {
            var typeInfo = type.GetTypeInfo();
            if (typeInfo.IsEnum || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type).GetTypeInfo().IsEnum))
            {
                var typeToParse = ReflectionUtils.IsNullableType(type)
                    ? Nullable.GetUnderlyingType(type)
                    : type;

                return value == null
                    ? null
                    : Enum.Parse(typeToParse, value.ToString(), true);
            }

            var primitiveConverter = this.FindPrimitiveConverter(type);
            if (primitiveConverter != null)
            {
                return primitiveConverter.Deserialize(value, type);
            }

            var valueDictionary = value as IDictionary<string, object>;
            if (valueDictionary == null)
            {
                return base.DeserializeObject(value, type, dateTimeStyles);
            }

            var javascriptConverter = this.FindJavaScriptConverter(type);
            if (javascriptConverter != null)
            {
                return javascriptConverter.Deserialize(valueDictionary, type);
            }

            if (!typeInfo.IsGenericType)
            {
                return base.DeserializeObject(value, type, dateTimeStyles);
            }

            var genericType = typeInfo.GetGenericTypeDefinition();
            var genericTypeConverter = this.FindJavaScriptConverter(genericType);

            if (genericTypeConverter == null)
            {
                return base.DeserializeObject(value, type, dateTimeStyles);
            }

            var values = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
            var genericArguments = type.GetGenericArguments();

            for (var i = 0; i < genericArguments.Length; i++)
            {
                var deserializedObject = this.DeserializeObject(valueDictionary.Values.ElementAt(i),
                    genericArguments[i], dateTimeStyles);

                values.Add(valueDictionary.Keys.ElementAt(i), deserializedObject);
            }

            return genericTypeConverter.Deserialize(values, type);
        }
예제 #9
0
 public static bool IsDate(string date, string format, IFormatProvider provider, DateTimeStyles styles)
 {
     if (string.IsNullOrEmpty(date))
     {
         return false;
     }
     DateTime minValue = DateTime.MinValue;
     return DateTime.TryParseExact(date, format, provider, styles, out minValue);
 }
        public static DateTimeOffset? DateTimeOffsetTryParseExactNullable(
            string value, IEnumerable<string> formats, IFormatProvider provider, DateTimeStyles styles)
        {
            DateTimeOffset result;
            if (!DateTimeOffset.TryParseExact(value, formats.ToArray(), provider, styles, out result))
                return null;

            return result;
        }
예제 #11
0
 internal static DateTime ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style) {
     DateTimeResult result = new DateTimeResult();       // The buffer to store the parsing result.
     result.Init();
     if (TryParseExact(s, format, dtfi, style, ref result)) {
         return result.parsedDate;
     }
     else {
         throw GetDateTimeParseException(ref result);
     }
 }
예제 #12
0
 internal static bool TryParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style, out DateTime result) {
     result = DateTime.MinValue;
     DateTimeResult resultData = new DateTimeResult();       // The buffer to store the parsing result.
     resultData.Init();
     if (TryParseExact(s, format, dtfi, style, ref resultData)) {
         result = resultData.parsedDate;
         return true;
     }
     return false;
 }
예제 #13
0
        /// <summary>
        ///     Converts the specified string representation of a date and time to its <see cref="DateTime" /> equivalent using the
        ///     specified culture-specific format information and formatting style, and returns a value that indicates whether the
        ///     conversion succeeded.
        /// </summary>
        /// <exception cref="ArgumentNullException">The value can not be null.</exception>
        /// <exception cref="ArgumentNullException">The format provider can not be null.</exception>
        /// <param name="value">A <see cref="String" /> containing a date and time to convert.</param>
        /// <param name="formatProvider">
        ///     An object that supplies culture-specific formatting information about
        ///     <paramref name="value" />.
        /// </param>
        /// <param name="dateTimeStyle">
        ///     A bitwise combination of enumeration values that defines how to interpret the parsed date in relation to the
        ///     current time zone or the current date.
        ///     A typical value to specify is <see cref="DateTimeStyles.None" />.
        /// </param>
        /// <param name="result">
        ///     When this method returns, contains the <see cref="DateTime" /> value equivalent to the date and time contained in
        ///     <paramref name="value" />, if the conversion succeeded, or
        ///     <see cref="DateTime.MinValue" /> if the conversion failed. The conversion fails if the <paramref name="value" />
        ///     parameter is
        ///     <value>null</value>
        ///     , is an empty string (""),
        ///     or does not contain a valid string representation of a date and time. This parameter is passed uninitialized.
        /// </param>
        /// <returns>
        ///     <value>true</value>
        ///     if the s parameter was converted successfully; otherwise,
        ///     <value>false</value>
        ///     .
        /// </returns>
        public static Boolean TryParsDateTime( this String value,
                                               IFormatProvider formatProvider,
                                               DateTimeStyles dateTimeStyle,
                                               out DateTime result )
        {
            value.ThrowIfNull( nameof( value ) );
            formatProvider.ThrowIfNull( nameof( formatProvider ) );

            return DateTime.TryParse( value, formatProvider, dateTimeStyle, out result );
        }
예제 #14
0
 /// <remarks>
 /// This method uses the
 /// <see cref="DateTime.Parse(string,IFormatProvider,DateTimeStyles)"/>
 /// method to convert the "state" into its <see cref="Guid"/>. Exceptions
 /// throwed by this method will be propagated to the caller.
 /// </remarks>
 public virtual bool StateByName(string name, DateTimeStyles styles,
   out DateTime state) {
   string s;
   if (StateByName(name, out s)) {
     state = DateTime.Parse(s, null, styles);
     return true;
   }
   state = DateTime.MinValue;
   return false;
 }
        /// <summary>
        ///     Converts the specified string representation of a date and time to its DateTime equivalent using the specified
        ///     format,
        ///     culture-specific format information, and style.
        ///     The format of the string representatiomust match the specified format exactly.
        ///     The method returns a value that indicates whether the conversion succeeded.
        /// </summary>
        /// <exception cref="ArgumentNullException">value can not be null.</exception>
        /// <exception cref="ArgumentNullException">format can not be null.</exception>
        /// <exception cref="ArgumentNullException">format provider can not be null.</exception>
        /// <param name="value">A <see cref="String" /> containing a date and time to convert.</param>
        /// <param name="format">The required format of s. See the Remarks section for more information.</param>
        /// <param name="formatProvider">
        ///     An object that supplies culture-specific formatting information about
        ///     <paramref name="value" />.
        /// </param>
        /// <param name="dateTimeStyle">
        ///     A bitwise combination of one or more enumeration values that indicate the permitted format
        ///     of <paramref name="value" />.
        /// </param>
        /// <param name="outValue">
        ///     When this method returns, contains the s<see cref="DateTime" /> value equivalent to the date and time contained in
        ///     <paramref name="value" />,
        ///     if the conversion succeeded, or <see cref="DateTime.MinValue" /> if the conversion failed.
        ///     The conversion fails if either the s or format parameter is null, is an empty string, or does not contain a date
        ///     and time that correspond to the pattern specified in format.
        ///     This parameter is passed uninitialized.
        /// </param>
        /// <returns>Returns true if the parsing was successful, otherwise false.</returns>
        public static Boolean TryParsDateTimeExact( this String value,
                                                    String format,
                                                    IFormatProvider formatProvider,
                                                    DateTimeStyles dateTimeStyle,
                                                    out DateTime outValue )
        {
            value.ThrowIfNull( nameof( value ) );
            format.ThrowIfNull( nameof( format ) );
            formatProvider.ThrowIfNull( nameof( formatProvider ) );

            return DateTime.TryParseExact( value, format, formatProvider, dateTimeStyle, out outValue );
        }
예제 #16
0
        /// <summary>
        /// Convert from java based date to DateTime.
        /// </summary>
        private static DateTime FromParsedDate(Date value, string originalString, DateTimeStyles style, DateFormat formatter, bool forceRoundtripKind, bool useUtc)
        {
            bool assumeLocal = (style & DateTimeStyles.AssumeLocal) != 0;
            bool assumeUtc = useUtc || (style & DateTimeStyles.AssumeUniversal) != 0;
            bool roundtripKind = forceRoundtripKind || (style & DateTimeStyles.RoundtripKind) != 0;

            var millis = value.Time;
            var ticks = (millis + DateTime.EraDifferenceInMs) * TimeSpan.TicksPerMillisecond;

            //long offset = 0L;
            DateTimeKind kind;

            if (roundtripKind)
            {
                var tz = formatter.TimeZone;
                if(tz.RawOffset == 0 || originalString.EndsWith("Z"))
                    kind = DateTimeKind.Utc;
                else if(tz.RawOffset == TimeZone.Default.RawOffset)
                    kind = DateTimeKind.Local;
                else
                    kind = DateTimeKind.Unspecified;
            }
            else if (assumeUtc)
            {
                kind = DateTimeKind.Utc;
            }
            else if (assumeLocal)
            {
                kind = DateTimeKind.Local;
            }
            else
            {
                kind = DateTimeKind.Unspecified;
            }

            DateTime result;

            if (millis == DateTime.MinValueJavaMillies)
                result = new DateTime(0L, kind);
            else
            {
                result = new DateTime(ticks, kind);
            }


            if ((style & DateTimeStyles.AdjustToUniversal) != 0)
                result = result.ToUniversalTime();
            else if (assumeUtc) // no typo, but bad naming/semantics in the BCL
                result = result.ToLocalTime();

            return result;
        }
예제 #17
0
 internal static DateTime ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style, out TimeSpan offset) {
     DateTimeResult result = new DateTimeResult();       // The buffer to store the parsing result.
     offset = TimeSpan.Zero;
     result.Init();
     result.flags |= ParseFlags.CaptureOffset;
     if (TryParseExact(s, format, dtfi, style, ref result)) {
         offset = result.timeZoneOffset;
         return result.parsedDate;
     }
     else {
         throw GetDateTimeParseException(ref result);
     }
 }
 public static bool TryParse(string s, DateTimeFormatInfo dateTimeFormatInfo, DateTimeStyles dateTimeStyles, out SystemDateTime dateTime)
 {
     try
     {
         dateTime = SystemDateTime.Parse(s, dateTimeFormatInfo, dateTimeStyles);
         return true;
     }
     catch (FormatException)
     {
         dateTime = SystemDateTime.MinValue;
         return false;
     }
 }
예제 #19
0
 internal static bool TryParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style, out DateTime result, out TimeSpan offset) {
     result = DateTime.MinValue;
     offset = TimeSpan.Zero;
     DateTimeResult resultData = new DateTimeResult();       // The buffer to store the parsing result.
     resultData.Init();
     resultData.flags |= ParseFlags.CaptureOffset;
     if (TryParseExact(s, format, dtfi, style, ref resultData)) {
         result = resultData.parsedDate;
         offset = resultData.timeZoneOffset;
         return true;
     }
     return false;
 }
 internal static bool TryParseExact(String s, String format, IFormatProvider provider, DateTimeStyles style, out DateTime result)
 {
     DateTimeFormatInfo dtfi = provider == null ? DateTimeFormatInfo.CurrentInfo : DateTimeFormatInfo.GetInstance(provider);
     result = DateTime.MinValue;
     DateTimeResult resultData = new DateTimeResult();       // The buffer to store the parsing result.
     resultData.Init();
     if (TryParseExact(s, format, dtfi, style, ref resultData))
     {
         result = resultData.parsedDate;
         return true;
     }
     return false;
 }
예제 #21
0
        /// <summary>
        ///     Converts the given string to a date time value.
        /// </summary>
        /// <exception cref="ArgumentNullException">The value can not be null.</exception>
        /// <exception cref="ArgumentNullException">The format provider can not be null.</exception>
        /// <param name="value">The string to convert.</param>
        /// <param name="formatProvider">The format provider.</param>
        /// <param name="dateTimeStyle">The date time style.</param>
        /// <param name="defaultValue">The default value, returned if the parsing fails.</param>
        /// <returns>The date time value.</returns>
        public static DateTime SaveToDateTime( this String value,
                                               IFormatProvider formatProvider,
                                               DateTimeStyles dateTimeStyle,
                                               DateTime? defaultValue = null )
        {
            value.ThrowIfNull( nameof( value ) );
            formatProvider.ThrowIfNull( nameof( formatProvider ) );

            DateTime outValue;
            return value.TryParsDateTime( formatProvider, dateTimeStyle, out outValue )
                ? outValue
                : ( defaultValue ?? outValue );
        }
            internal static DateTime ParseExact(String s, String format, IFormatProvider provider, DateTimeStyles style)
            {
                DateTimeFormatInfo dtfi = provider == null ? DateTimeFormatInfo.CurrentInfo : DateTimeFormatInfo.GetInstance(provider);

                DateTimeResult result = new DateTimeResult();       // The buffer to store the parsing result.
                result.Init();
                if (TryParseExact(s, format, dtfi, style, ref result))
                {
                    return result.parsedDate;
                }
                else
                {
                    throw GetDateTimeParseException(ref result);
                }
            }
예제 #23
0
        /// <summary>
        /// Initializes a new <see cref="DateTimeFormat"/> with the specified
        /// formatString and formatProvider.
        /// </summary>
        /// <param name="formatString">Specifies the formatString to be used.</param>
        /// <param name="formatProvider">Specifies the formatProvider to be used.</param>
        public DateTimeFormat(string formatString, IFormatProvider formatProvider)
        {
            if (formatString == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("formatString");
            }

            if (formatProvider == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("formatProvider");
            }

            _formatString = formatString;
            _formatProvider = formatProvider;
            _dateTimeStyles = DateTimeStyles.RoundtripKind;
        }
예제 #24
0
     public ParseBehaviorAttribute(
   string cultureName,
   NumberStyles numberStyle,
   DateTimeStyles dateTimeStyle,
   string dateTimeFormat,
   string pattern,
   int length
 )
     {
         CultureName = cultureName;
           NumberStyle = numberStyle;
           DateTimeStyle = dateTimeStyle;
           DateTimeFormat = dateTimeFormat;
           Pattern = pattern;
           Length = length;
     }
		/// <param name="format">The format to use for the conversion.</param>
		/// <param name="dateTimeFormatInfo">The <see cref="System.Globalization.DateTimeFormatInfo"/> that this <see cref="DateTimeConversionRule"/> uses to convert with.</param>
		/// <param name="dateTimeStyles">The <see cref="System.Globalization.DateTimeStyles"/> that this <see cref="DateTimeConversionRule"/> uses to convert with.</param>
		public DateTimeConversionRule(string format, DateTimeFormatInfo dateTimeFormatInfo, DateTimeStyles dateTimeStyles)
            : base(TypePointers.StringType)
        {
        	
			Format = format;
			if (dateTimeFormatInfo == null)
        	{
        		DateTimeFormatInfo = DateTimeFormatInfo.CurrentInfo;
        	}
        	else
        	{
				DateTimeFormatInfo = dateTimeFormatInfo;
        	}

        	DateTimeStyles = dateTimeStyles;
        }
예제 #26
0
        /// <summary>
        /// Tries to convert the string FTP date representation  into a date time object
        /// </summary>
        /// <param name="date">The date</param>
        /// <param name="style">UTC/Local Time</param>
        /// <returns>A date time object representing the date, DateTime.MinValue if there was a problem</returns>
        public static DateTime GetFtpDate(this string date, DateTimeStyles style)
        {
            string[] formats = new string[] {
                "yyyyMMddHHmmss",
                "yyyyMMddHHmmss.fff",
                "MMM dd  yyyy",
                "MMM dd HH:mm"
            };
            DateTime parsed;

            if (DateTime.TryParseExact(date, formats, CultureInfo.InvariantCulture, style, out parsed)) {
                return parsed;
            }

            return DateTime.MinValue;
        }
예제 #27
0
        /// <summary>
        /// Tries to convert the string FTP date representation  into a date time object
        /// </summary>
        /// <param name="date">The date</param>
        /// <param name="style">UTC/Local Time</param>
        /// <returns>A date time object representing the date, DateTime.MinValue if there was a problem</returns>
        public static DateTime GetFtpDate(this string date, DateTimeStyles style)
        {
            var formats = new[]
                              {
                                  "yyyyMMddHHmmss",
                                  "yyyyMMddHHmmss.fff",
                                  "MMM dd  yyyy",
                                  "MMM dd yyyy",
                                  "MMM dd HH:mm",
                                  "MMM  d HH:mm",
                                  "YYYY-MM-DD-HH:mm"
                              };
            DateTime parsed;

            return DateTime.TryParseExact(date, formats, CultureInfo.InvariantCulture, style, out parsed) ||
                   DateTime.TryParseExact(date, formats, CultureInfo.CurrentUICulture, style, out parsed)
                       ? parsed
                       : DateTime.MinValue;
        }
예제 #28
0
        /// <summary>
        /// Tries to parse a datetime value from the string.
        /// </summary>
        /// <param name="dateTimeString">string to parse</param>
        /// <param name="useXmlConversion">if true, uses XmlConvert. else, uses JSON.</param>
        /// <returns>value if found, otherwise null.</returns>
        public static DateTime? TryGetDateTimeValue(string dateTimeString, bool useXmlConversion = false, IFormatProvider formatter = null, DateTimeStyles parserStyles = DateTimeStyles.None)
        {
            DateTime? value = null;

            if (!string.IsNullOrEmpty(dateTimeString))
            {
                try
                {
                    if (useXmlConversion)
                    {
                        value = XmlConvert.ToDateTimeOffset(dateTimeString).DateTime;
                    }
                    else
                    {
                        DateTime parsed;
                        if (formatter != null && parserStyles != DateTimeStyles.None)
                        {
                            if (DateTime.TryParse(dateTimeString, formatter, parserStyles, out parsed))
                            {
                                value = parsed;
                            }
                        }
                        else
                        {
                            if (DateTime.TryParse(dateTimeString, out parsed))
                            {
                                value = parsed;
                            }
                        }
                    }
                }
                catch (ArgumentNullException ex)
                {
                    Debug.Fail(ex.ToString());
                }
                catch (FormatException ex)
                {
                    Debug.Fail(ex.ToString());
                }
            }

            return value;
        }
예제 #29
0
        public static bool TryParse(string input, IFormatProvider provider, DateTimeStyles styles, out DateTime result)
        {
            bool success = false;

            try
            {
                result = DateTime.Parse(input, provider, styles);
                success = true;
            }
            catch (FormatException)
            {
                result = new DateTime();
            }
            catch (InvalidCastException)
            {
                result = new DateTime();
            }

            return success;
        }
        private static DateTime ParseDateTime(string dateToParse, DateTime defaultDateTime, DateTimeFormatInfo formatInfo, DateTimeStyles style, string context)
        {
            DateTime DT;

            if (DateTime.TryParse(dateToParse, formatInfo, style, out DT))
            {
                return(DT);
            }
            CultureInfo defaultCulture = CultureInfo.CurrentCulture;

            if (DateTime.TryParse(dateToParse, out DT))
            {
                return(DT);
            }
            Debug.LogError("Date Time: " + dateToParse + " Failed to parse correctly, resetting to defualt value: " + defaultDateTime + " Context: " + context + " Current culture: " + CultureInfo.CurrentCulture.Name);
            return(defaultDateTime);
        }
 /// <summary>
 /// The <see cref="DateTimeStyles"/> to use when type converting.
 /// This is used when doing any <see cref="DateTime"/> conversions.
 /// </summary>
 /// <param name="dateTimeStyles">The date time styles.</param>
 public DateTimeStylesAttribute(DateTimeStyles dateTimeStyles)
 {
     DateTimeStyles = dateTimeStyles;
 }
예제 #32
0
        public static bool TryParseExact(
            ReadOnlySpan <char> input, string?[]?formats, IFormatProvider?formatProvider, DateTimeStyles styles, out DateTimeOffset result)
        {
            styles = ValidateStyles(styles, nameof(styles));
            bool parsed = DateTimeParse.TryParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out DateTime dateResult, out TimeSpan offset);

            result = new DateTimeOffset(dateResult.Ticks, offset);
            return(parsed);
        }
 public NullableDateTimeConverter(string dateTimeFormat, IFormatProvider formatProvider, DateTimeStyles dateTimeStyles)
     : base(new DateTimeConverter(dateTimeFormat, formatProvider, dateTimeStyles))
 {
 }
예제 #34
0
        // Currently, custom format and normal date time format except 'o' or 'O' 's' are NOT supported.
        public static TimestampParseResult TryParseExact(string input, string format, IFormatProvider formatProvider, DateTimeStyles styles, out Timestamp result)
        {
            if (format != "o" && format != "O" && format != "s")
            {
                result = default(Timestamp);
                return(TimestampParseResult.UnsupportedFormat);
            }

            var numberFormat = NumberFormatInfo.GetInstance(formatProvider);

            var position = 0;

            if (!ParseWhitespace(input, ref position, (styles & DateTimeStyles.AllowLeadingWhite) != 0, /* isTrailing */ false))
            {
                result = default(Timestamp);
                return(TimestampParseResult.LeadingWhitespaceNotAllowed);
            }

            long year;

            if (!ParseYear(input, ref position, numberFormat, out year))
            {
                result = default(Timestamp);
                return(TimestampParseResult.InvalidYear);
            }

            if (!ParseDelimiter(input, ref position, DateDelimiter))
            {
                result = default(Timestamp);
                return(TimestampParseResult.InvalidYearMonthDeilimiter);
            }

            var isLeapYear = Timestamp.IsLeapYearInternal(year);

            int month;

            if (!ParseDigitRange(input, 2, ref position, 1, 12, out month))
            {
                result = default(Timestamp);
                return(TimestampParseResult.InvalidMonth);
            }

            if (!ParseDelimiter(input, ref position, DateDelimiter))
            {
                result = default(Timestamp);
                return(TimestampParseResult.InvalidMonthDayDelimiter);
            }

            int day;

            if (!ParseDay(input, ref position, month, isLeapYear, out day))
            {
                result = default(Timestamp);
                return(TimestampParseResult.InvalidDay);
            }

            if (!ParseDelimiter(input, ref position, DateTimeDelimiter))
            {
                result = default(Timestamp);
                return(TimestampParseResult.InvalidDateTimeDelimiter);
            }

            int hour;

            if (!ParseDigitRange(input, 2, ref position, 0, 23, out hour))
            {
                result = default(Timestamp);
                return(TimestampParseResult.InvalidHour);
            }

            if (!ParseDelimiter(input, ref position, TimeDelimiter))
            {
                result = default(Timestamp);
                return(TimestampParseResult.InvalidHourMinuteDelimiter);
            }

            int minute;

            if (!ParseDigitRange(input, 2, ref position, 0, 59, out minute))
            {
                result = default(Timestamp);
                return(TimestampParseResult.InvalidMinute);
            }

            if (!ParseDelimiter(input, ref position, TimeDelimiter))
            {
                result = default(Timestamp);
                return(TimestampParseResult.InvalidMinuteSecondDelimiter);
            }

            int second;

            if (!ParseDigitRange(input, 2, ref position, 0, 59, out second))
            {
                result = default(Timestamp);
                return(TimestampParseResult.InvalidSecond);
            }

            var nanosecond = 0;

            if (format != "s")
            {
                // "o" or "O"
                if (!ParseDelimiter(input, ref position, SubsecondDelimiter))
                {
                    result = default(Timestamp);
                    return(TimestampParseResult.InvalidSubsecondDelimiter);
                }

                if (!ParseDigitRange(input, 9, ref position, 0, 999999999, out nanosecond))
                {
                    result = default(Timestamp);
                    return(TimestampParseResult.InvalidNanoSecond);
                }
            }

            if (!ParseDelimiter(input, ref position, UtcSign))
            {
                result = default(Timestamp);
                return(TimestampParseResult.MissingUtcSign);
            }

            if (!ParseWhitespace(input, ref position, (styles & DateTimeStyles.AllowTrailingWhite) != 0, /* isTrailing */ true))
            {
                result = default(Timestamp);
                return(TimestampParseResult.TrailingWhitespaceNotAllowed);
            }

            if (position != input.Length)
            {
                result = default(Timestamp);
                return(TimestampParseResult.ExtraCharactors);
            }

            var components = new Timestamp.Value();

            components.Year        = year;
            components.Month       = month;
            components.Day         = day;
            components.Hour        = hour;
            components.Minute      = minute;
            components.Second      = second;
            components.Nanoseconds = unchecked (( uint )nanosecond);

            try
            {
                result = Timestamp.FromComponents(ref components, isLeapYear);
            }
            catch (OverflowException)
            {
                result = default(Timestamp);
                return(TimestampParseResult.YearOutOfRange);
            }

            return(TimestampParseResult.Success);
        }
예제 #35
0
        public static DateTimeOffset ParseExact(string input, string[] formats, IFormatProvider?formatProvider, DateTimeStyles styles)
        {
            styles = ValidateStyles(styles, nameof(styles));
            if (input == null)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input);
            }

            TimeSpan offset;
            DateTime dateResult = DateTimeParse.ParseExactMultiple(input,
                                                                   formats,
                                                                   DateTimeFormatInfo.GetInstance(formatProvider),
                                                                   styles,
                                                                   out offset);

            return(new DateTimeOffset(dateResult.Ticks, offset));
        }
        public static DateTime?ToNullableDateTime(this object objeto, CultureInfo culture, DateTimeStyles style = DateTimeStyles.None, bool enableError = false)
        {
            try
            {
                DateTime?saida = null;

                if (DateTime.TryParse(objeto?.ToString(), culture, style, out DateTime teste))
                {
                    saida = teste;
                }
                else if (enableError)
                {
                    throw new Exception("A conversão falhou!");
                }

                return(saida);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #37
0
        public static DateTimeOffset ParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles)
        {
            styles = ValidateStyles(styles, nameof(styles));
            TimeSpan offset;
            DateTime dateResult = DateTimeParse.ParseExactMultiple(input,
                                                                   formats,
                                                                   DateTimeFormatInfo.GetInstance(formatProvider),
                                                                   styles,
                                                                   out offset);

            return(new DateTimeOffset(dateResult.Ticks, offset));
        }
예제 #38
0
        public static bool TryParseExact(string?input, string?[]?formats, IFormatProvider?formatProvider, DateTimeStyles styles,
                                         out DateTimeOffset result)
        {
            styles = ValidateStyles(styles, nameof(styles));
            if (input == null)
            {
                result = default;
                return(false);
            }

            TimeSpan offset;
            DateTime dateResult;
            bool     parsed = DateTimeParse.TryParseExactMultiple(input,
                                                                  formats,
                                                                  DateTimeFormatInfo.GetInstance(formatProvider),
                                                                  styles,
                                                                  out dateResult,
                                                                  out offset);

            result = new DateTimeOffset(dateResult.Ticks, offset);
            return(parsed);
        }
 public DateTimeOffset?Parse(IFormatProvider provider, DateTimeStyles styles = DateTimeStyles.AllowWhiteSpaces)
 {
     return(DateTimeStringParser.DateTimeOffsetTryParseNullable(_input, provider, styles));
 }
예제 #40
0
 ValueTask <DateTimeOffset> IAsyncBinaryReader.ReadDateTimeOffsetAsync(StringLengthEncoding lengthFormat, DecodingContext context, string[] formats, DateTimeStyles style, IFormatProvider?provider, CancellationToken token)
 => EndOfStream <DateTimeOffset>();
예제 #41
0
        public static void ParseExact_Span_ValidInput_Succeeds(string input, string format, CultureInfo culture, DateTimeStyles style, DateTime?expected)
        {
            DateTime result1 = DateTime.ParseExact(input.AsReadOnlySpan(), format, culture, style);
            DateTime result2 = DateTime.ParseExact(input.AsReadOnlySpan(), new[] { format }, culture, style);

            Assert.True(DateTime.TryParseExact(input.AsReadOnlySpan(), format, culture, style, out DateTime result3));
            Assert.True(DateTime.TryParseExact(input.AsReadOnlySpan(), new[] { format }, culture, style, out DateTime result4));

            Assert.Equal(result1, result2);
            Assert.Equal(result1, result3);
            Assert.Equal(result1, result4);

            if (expected != null) // some inputs don't roundtrip well
            {
                // Normalize values to make comparison easier
                if (expected.Value.Kind != DateTimeKind.Utc)
                {
                    expected = expected.Value.ToUniversalTime();
                }
                if (result1.Kind != DateTimeKind.Utc)
                {
                    result1 = result1.ToUniversalTime();
                }

                Assert.Equal(expected, result1);
            }
        }
예제 #42
0
        public static void ParseExact_Span_InvalidInputs_Fail(string input, string format, CultureInfo culture, DateTimeStyles style)
        {
            Assert.Throws <FormatException>(() => DateTime.ParseExact(input.AsReadOnlySpan(), format, culture, style));
            Assert.Throws <FormatException>(() => DateTime.ParseExact(input.AsReadOnlySpan(), new[] { format }, culture, style));

            Assert.False(DateTime.TryParseExact(input.AsReadOnlySpan(), format, culture, style, out DateTime result));
            Assert.False(DateTime.TryParseExact(input.AsReadOnlySpan(), new[] { format }, culture, style, out result));
        }
 public DateTimeOffset?ParseInvariant(DateTimeStyles styles = DateTimeStyles.AllowWhiteSpaces)
 {
     return(Parse(CultureInfo.InvariantCulture, styles));
 }
        public static bool TryParseExact([NotNullWhen(true)] string?input, [NotNullWhen(true)] string?format, IFormatProvider?formatProvider, DateTimeStyles styles,
                                         out DateTimeOffset result)
        {
            styles = ValidateStyles(styles, nameof(styles));
            if (input == null || format == null)
            {
                result = default;
                return(false);
            }

            bool parsed = DateTimeParse.TryParseExact(input,
                                                      format,
                                                      DateTimeFormatInfo.GetInstance(formatProvider),
                                                      styles,
                                                      out DateTime dateResult,
                                                      out TimeSpan offset);

            result = new DateTimeOffset(dateResult.Ticks, offset);
            return(parsed);
        }
예제 #45
0
    static public DateTime ParseDateTime(this string s, DateTime def, CultureInfo ci, DateTimeStyles ds = DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal)
    {
        DateTime ret;

        if (!DateTime.TryParse(s, ci, ds, out ret))
        {
            ret = def;
        }
        return(ret);
    }
예제 #46
0
 public void EnumNames_MatchExpectedValues(DateTimeStyles style, ulong expected)
 {
     Assert.Equal(expected, (ulong)style);
 }
 public DateTimeOffset?ParseExact(IEnumerable <string> formats, IFormatProvider provider, DateTimeStyles styles = DateTimeStyles.AllowWhiteSpaces)
 {
     return(DateTimeStringParser.DateTimeOffsetTryParseExactNullable(_input, formats, provider, styles));
 }
예제 #48
0
 public static DateTime?ParseDate(this string str, string format, IFormatProvider provider = null, DateTimeStyles style = DateTimeStyles.AssumeLocal) =>
 DateTime.TryParseExact(str, format, provider ?? CultureInfo.CurrentCulture, style, out var i) ? i : (DateTime?)null;
예제 #49
0
파일: Valid.cs 프로젝트: zyj0021/Bing
        /// <summary>
        /// 是否日期
        /// </summary>
        /// <param name="value">日期字符串</param>
        /// <param name="format">格式化字符串</param>
        /// <param name="provider">格式化提供者</param>
        /// <param name="styles">日期格式</param>
        /// <returns></returns>
        public static bool IsDate(string value, string format, IFormatProvider provider, DateTimeStyles styles)
        {
            if (value.IsEmpty())
            {
                return(false);
            }
            DateTime minValue;

            return(DateTime.TryParseExact(value, format, provider, styles, out minValue));
        }
예제 #50
0
        /// <summary>
        /// Constructs a MobileProvision from an xml blob extracted from the real ASN.1 file
        /// </summary>
        public MobileProvision(string EmbeddedPListText)
        {
            Data = new Utilities.PListHelper(EmbeddedPListText);

            // Now extract things

            // Key: ApplicationIdentifierPrefix, Array<String>
            List <string> PrefixList = Data.GetArray("ApplicationIdentifierPrefix", "string");

            if (PrefixList.Count > 1)
            {
                Program.Warning("Found more than one entry for ApplicationIdentifierPrefix in the .mobileprovision, using the first one found");
            }

            if (PrefixList.Count > 0)
            {
                ApplicationIdentifierPrefix = PrefixList[0];
            }

            // Example date string from the XML: "2014-06-30T20:45:55Z";
            DateTimeStyles AppleDateStyle = DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal;

            string CreationDateString;

            if (Data.GetDate("CreationDate", out CreationDateString))
            {
                CreationDate = DateTime.Parse(CreationDateString, CultureInfo.InvariantCulture, AppleDateStyle);
            }

            string ExpirationDateString;

            if (Data.GetDate("ExpirationDate", out ExpirationDateString))
            {
                ExpirationDate = DateTime.Parse(ExpirationDateString, CultureInfo.InvariantCulture, AppleDateStyle);
            }

            // Key: DeveloperCertificates, Array<Data> (uuencoded)
            string        CertificatePassword = "";
            List <string> CertificateList     = Data.GetArray("DeveloperCertificates", "data");

            foreach (string EncodedCert in CertificateList)
            {
                byte[] RawCert = Convert.FromBase64String(EncodedCert);
                DeveloperCertificates.Add(new X509Certificate2(RawCert, CertificatePassword));
            }

            // Key: Name, String
            if (!Data.GetString("Name", out ProvisionName))
            {
                ProvisionName = "(unknown)";
            }

            // Key: ProvisionedDevices, Array<String>
            ProvisionedDeviceIDs = Data.GetArray("ProvisionedDevices", "string");

            // Key: application-identifier, Array<String>
            Utilities.PListHelper XCentPList = null;
            Data.ProcessValueForKey("Entitlements", "dict", delegate(XmlNode ValueNode)
            {
                XCentPList = Utilities.PListHelper.CloneDictionaryRootedAt(ValueNode);
            });

            // Modify the application-identifier to be fully qualified if needed
            if (!XCentPList.GetString("application-identifier", out ApplicationIdentifier))
            {
                ApplicationIdentifier = "(unknown)";
            }

            // check for get-task-allow
            bDebug = XCentPList.GetBool("get-task-allow");

            if (!Data.GetString("UUID", out UUID))
            {
                UUID = "(unkown)";
            }

            List <string> Platforms = Data.GetArray("Platform", "string");

            if (Platforms.Contains("iOS"))
            {
                Platform = "IOS";
            }
            else if (Platforms.Contains("tvOS"))
            {
                Platform = "TVOS";
            }
            else
            {
                Platform = "";
            }
        }
예제 #51
0
        public static DateTimeOffset ParseExact(ReadOnlySpan <char> input, string[] formats, IFormatProvider?formatProvider, DateTimeStyles styles = DateTimeStyles.None)
        {
            styles = ValidateStyles(styles, nameof(styles));
            DateTime dateResult = DateTimeParse.ParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out TimeSpan offset);

            return(new DateTimeOffset(dateResult.Ticks, offset));
        }
예제 #52
0
 public static IOption <DateTime> ToDateTime(this string s, IFormatProvider format = null, DateTimeStyles style = DateTimeStyles.None)
 {
     return(Tryer.Invoke <string, IFormatProvider, DateTimeStyles, DateTime>(DateTime.TryParse, s, format, style));
 }
예제 #53
0
        private static DateTimeOffset ToDateTimeOffsetInternal(object value, IFormatProvider provider, DateTimeStyles styles)
        {
            if (value is DateTime)
            {
                return((DateTimeOffset)value);
            }

            return(DateTimeOffset.Parse(value.ToString(), provider, styles));
        }
 public DateTimeOffset?ParseExactInvariant(string format, DateTimeStyles styles = DateTimeStyles.AllowWhiteSpaces)
 {
     return(ParseExact(format, CultureInfo.InvariantCulture, styles));
 }
예제 #55
0
        public static DateTime AsDateTimeFormat(this string val, DateTime dflt, string fmt, DateTimeStyles fmtStyles = DateTimeStyles.None)
        {
            DateTime result;

            return(DateTime.TryParseExact(val, fmt, null, fmtStyles, out result) ? result : dflt);
        }
 public DateTimeOffset?ParseExactInvariant(IEnumerable <string> formats, DateTimeStyles styles = DateTimeStyles.AllowWhiteSpaces)
 {
     return(ParseExact(formats, CultureInfo.InvariantCulture, styles));
 }
예제 #57
0
 /// <summary>
 /// Converts given string to <see cref="DateTime"/> or returns <paramref name="defaultValue"/>
 /// </summary>
 /// <param name="s"></param>
 /// <param name="style"></param>
 /// <param name="provider"></param>
 /// <param name="defaultValue"></param>
 /// <returns></returns>
 public static DateTime ToDate(this string s, DateTimeStyles style, IFormatProvider provider, DateTime defaultValue = default)
 {
     return(DateTime.TryParse(s, provider, style, out DateTime res) ? res : defaultValue);
 }
 public DateTimeOffset?ParseCulture(DateTimeStyles styles = DateTimeStyles.AllowWhiteSpaces)
 {
     return(Parse(CultureInfo.CurrentCulture, styles));
 }
예제 #59
0
        public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles,
                                            out DateTimeOffset result)
        {
            styles = ValidateStyles(styles, nameof(styles));
            TimeSpan offset;
            DateTime dateResult;
            Boolean  parsed = DateTimeParse.TryParseExactMultiple(input,
                                                                  formats,
                                                                  DateTimeFormatInfo.GetInstance(formatProvider),
                                                                  styles,
                                                                  out dateResult,
                                                                  out offset);

            result = new DateTimeOffset(dateResult.Ticks, offset);
            return(parsed);
        }
예제 #60
-1
        /// <summary>
        /// Initializes a new instance of the <see cref="GlobalizationConfiguration"/> class
        /// </summary>
        /// <param name="supportedCultureNames">An array of supported cultures</param>
        /// <param name="defaultCulture">The default culture of the application</param>
        /// <param name="dateTimeStyles">The <see cref="DateTimeStyles"/> that should be used for date parsing.</param>
        public GlobalizationConfiguration(IEnumerable<string> supportedCultureNames, string defaultCulture = null, DateTimeStyles? dateTimeStyles = null)
        {
            if (supportedCultureNames == null)
            {
                throw new ConfigurationException("Invalid Globalization configuration. You must support at least one culture");
            }

            supportedCultureNames = supportedCultureNames.Where(cultureName => !string.IsNullOrEmpty(cultureName)).ToArray();

            if (!supportedCultureNames.Any())
            {
                throw new ConfigurationException("Invalid Globalization configuration. You must support at least one culture");
            }

            if (string.IsNullOrEmpty(defaultCulture))
            {
                defaultCulture = supportedCultureNames.First();
            }

            if (!supportedCultureNames.Contains(defaultCulture, StringComparer.OrdinalIgnoreCase))
            {
                throw new ConfigurationException("Invalid Globalization configuration. " + defaultCulture + " does not exist in the supported culture names");
            }

            this.DateTimeStyles = dateTimeStyles ?? Default.DateTimeStyles;
            this.DefaultCulture = defaultCulture;
            this.SupportedCultureNames = supportedCultureNames;
        }