Exemple #1
0
 private static TimeSpan ConvertResult(DurationVisitor visitor)
 {
     return(TimeSpan.Zero
            .Add(TimeSpan.FromDays(visitor.Weeks * 7))
            .Add(TimeSpan.FromDays(visitor.Days))
            .Add(TimeSpan.FromHours(visitor.Hours))
            .Add(TimeSpan.FromMinutes(visitor.Minutes))
            .Add(TimeSpan.FromSeconds(visitor.Seconds)));
 }
Exemple #2
0
        /// <summary>
        /// Converts the ISO 8601 string representation of a duration to its equivalent
        /// .NET <see cref="TimeSpan"/> representation.
        /// A return value indicates whether the conversion succeeded or failed.
        /// </summary>
        /// <remarks>
        /// The year (Y) and month (M) designators are currently unsupported. If these
        /// designators are encountered, the method will return <see langword="false"/>.
        /// <para>
        /// These are problematic because of things like leap years, Daylight Savings Time, etc.
        /// More information is needed in order to convert to a <see cref="TimeSpan"/>;
        /// for that, a more powerful library such as NodaTime would be appropriate.
        /// </para>
        /// </remarks>
        /// <param name="duration">The ISO 8601 duration, excluding year (Y) and month (M) designators.
        /// </param>
        /// <param name="timeSpan">
        /// When the method returns, this parameter is set to the resulting <see cref="TimeSpan"/>
        /// if the conversion was successful, or <c>default(TimeSpan)</c> if the conversion was unsuccessful.</param>
        /// <returns><see langword="true"/> if the conversion succeeded; <see langword="false"/> otherwise.</returns>
        public static bool TryParse(string duration, out TimeSpan timeSpan)
        {
            timeSpan = default(TimeSpan);

            var result = DurationVisitor.Parse(duration);

            if (result.Valid)
            {
                timeSpan = ConvertResult(result);
            }

            return(result.Valid);
        }