/// <summary> /// Converts a Protobuf <see cref="ProtobufDuration"/> to a Noda Time <see cref="NodaDuration"/>. /// </summary> /// <remarks> /// Every valid Protobuf duration can be represented in Noda Time without loss of information. /// </remarks> /// <param name="duration">The duration to convert. Must not be null.</param> /// <exception cref="ArgumentException"><paramref name="duration"/> represents an invalid duration.</exception> /// <exception cref="ArgumentNullException"><paramref name="duration"/> is null.</exception> /// <returns>The Noda Time representation.</returns> public static NodaDuration ToNodaDuration(this ProtobufDuration duration) { Preconditions.CheckNotNull(duration, nameof(duration)); long seconds = duration.Seconds; long nanos = duration.Nanos; Preconditions.CheckArgument( seconds >= ProtobufDuration.MinSeconds && seconds <= ProtobufDuration.MaxSeconds, nameof(duration), "duration.Seconds out of range: {0}", seconds); Preconditions.CheckArgument( nanos > -ProtobufDuration.NanosecondsPerSecond && nanos < ProtobufDuration.NanosecondsPerSecond, nameof(duration), "duration.Nanos out of range: {0}", nanos); // If either sign is 0, we're fine. Otherwise, they should be the same. Multiplying them // together seems the easiest way to check that. Preconditions.CheckArgument(Math.Sign(seconds) * Math.Sign(nanos) != -1, nameof(duration), "duration.Seconds and duration.Nanos have different signs: {0}s {1}ns", seconds, nanos); return(NodaDuration.FromSeconds(seconds) + NodaDuration.FromNanoseconds(nanos)); }
/// <summary> /// Converts the given <see cref="TimeSpan"/> to a <see cref="Duration"/>. /// </summary> /// <param name="timeSpan">The time span to convert.</param> /// <returns>The converted duration.</returns> public static Duration ToDuration(this TimeSpan timeSpan) { return(Duration.FromTimeSpan(timeSpan)); }