DailyCalendar.cs 35.2 KB
Newer Older
M
Marko Lahma 已提交
1
#region License
M
Marko Lahma 已提交
2

M
Marko Lahma 已提交
3
/*
M
Marko Lahma 已提交
4
 * All content copyright Marko Lahma, unless otherwise indicated. All rights reserved.
M
Marko Lahma 已提交
5 6 7 8 9 10 11 12 13 14 15
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy
 * of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
M
Marko Lahma 已提交
16
 * under the License.
M
Marko Lahma 已提交
17
 *
M
Marko Lahma 已提交
18
 */
M
Marko Lahma 已提交
19

M
Marko Lahma 已提交
20 21 22
#endregion

using System.Globalization;
23
using System.Runtime.Serialization;
M
Marko Lahma 已提交
24 25
using System.Text;

M
Marko Lahma 已提交
26 27
using Quartz.Util;

28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
namespace Quartz.Impl.Calendar;

/// <summary>
/// This implementation of the Calendar excludes (or includes - see below) a
/// specified time range each day.
/// </summary>
/// <remarks>
/// For example, you could use this calendar to
/// exclude business hours (8AM - 5PM) every day. Each <see cref="DailyCalendar" />
/// only allows a single time range to be specified, and that time range may not
/// * cross daily boundaries (i.e. you cannot specify a time range from 8PM - 5AM).
/// If the property <see cref="InvertTimeRange" /> is <see langword="false" /> (default),
/// the time range defines a range of times in which triggers are not allowed to
/// * fire. If <see cref="InvertTimeRange" /> is <see langword="true" />, the time range
/// is inverted: that is, all times <i>outside</i> the defined time range
/// are excluded.
/// <para>
/// Note when using <see cref="DailyCalendar" />, it behaves on the same principals
/// as, for example, WeeklyCalendar defines a set of days that are
/// excluded <i>every week</i>. Likewise, <see cref="DailyCalendar" /> defines a
/// set of times that are excluded <i>every day</i>.
/// </para>
/// </remarks>
/// <author>Mike Funk</author>
/// <author>Aaron Craven</author>
/// <author>Marko Lahma (.NET)</author>
[Serializable]
55
public sealed class DailyCalendar : BaseCalendar
M
Marko Lahma 已提交
56
{
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    private const string InvalidHourOfDay = "Invalid hour of day: ";
    private const string InvalidMinute = "Invalid minute: ";
    private const string InvalidSecond = "Invalid second: ";
    private const string InvalidMillis = "Invalid millis: ";
    private const string InvalidTimeRange = "Invalid time range: ";
    private const string Separator = " - ";
    private const long OneMillis = 1;
    private const char Colon = ':';

    private const string TwoDigitFormat = "00";
    private const string ThreeDigitFormat = "000";

    // JsonProperty attributes are necessary because no public field/property exposes these directly
    // Adding RangeStartingTimeUTC and RangeEndingTimeUTC properties with getters/setters to control
    // these would remove the need for the attribute.
    private int rangeStartingHourOfDay;
    private int rangeStartingMinute;
    private int rangeStartingSecond;
    private int rangeStartingMillis;
    private int rangeEndingHourOfDay;
    private int rangeEndingMinute;
    private int rangeEndingSecond;
    private int rangeEndingMillis;

    private DailyCalendar()
    {
    }

M
Marko Lahma 已提交
85
    /// <summary>
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
    /// Create a <see cref="DailyCalendar" /> with a time range defined by the
    /// specified strings and no baseCalendar.
    ///	<paramref name="rangeStartingTime" /> and <paramref name="rangeEndingTime" />
    /// must be in the format &quot;HH:MM[:SS[:mmm]]&quot; where:
    /// <ul>
    ///     <li>
    ///         HH is the hour of the specified time. The hour should be
    ///          specified using military (24-hour) time and must be in the range
    ///          0 to 23.
    ///     </li>
    ///     <li>
    ///         MM is the minute of the specified time and must be in the range
    ///         0 to 59.
    ///     </li>
    ///     <li>
    ///         SS is the second of the specified time and must be in the range
    ///         0 to 59.
    ///     </li>
    ///     <li>
    ///         mmm is the millisecond of the specified time and must be in the
    ///         range 0 to 999.
    ///     </li>
    ///     <li>items enclosed in brackets ('[', ']') are optional.</li>
    ///     <li>
    ///         The time range starting time must be before the time range ending
    ///         time. Note this means that a time range may not cross daily
    ///         boundaries (10PM - 2AM)
    ///     </li>
    /// </ul>
M
Marko Lahma 已提交
115
    /// </summary>
116 117 118
    /// <param name="rangeStartingTime">The range starting time in millis.</param>
    /// <param name="rangeEndingTime">The range ending time in millis.</param>
    public DailyCalendar(string rangeStartingTime, string rangeEndingTime)
M
Marko Lahma 已提交
119
    {
120 121
        SetTimeRange(rangeStartingTime, rangeEndingTime);
    }
122

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
    /// <summary>
    /// Create a <see cref="DailyCalendar"/> with a time range defined by the
    /// specified strings and the specified baseCalendar.
    /// <paramref name="rangeStartingTime"/> and <paramref name="rangeEndingTime"/>
    /// must be in the format "HH:MM[:SS[:mmm]]" where:
    /// <ul>
    /// 		<li>
    /// HH is the hour of the specified time. The hour should be
    /// specified using military (24-hour) time and must be in the range
    /// 0 to 23.
    /// </li>
    /// 		<li>
    /// MM is the minute of the specified time and must be in the range
    /// 0 to 59.
    /// </li>
    /// 		<li>
    /// SS is the second of the specified time and must be in the range
    /// 0 to 59.
    /// </li>
    /// 		<li>
    /// mmm is the millisecond of the specified time and must be in the
    /// range 0 to 999.
    /// </li>
    /// 		<li>
    /// items enclosed in brackets ('[', ']') are optional.
    /// </li>
    /// 		<li>
    /// The time range starting time must be before the time range ending
    /// time. Note this means that a time range may not cross daily
    /// boundaries (10PM - 2AM)
    /// </li>
    /// 	</ul>
    /// </summary>
    /// <param name="baseCalendar">The base calendar for this calendar instance see BaseCalendar for more
    /// information on base calendar functionality.</param>
    /// <param name="rangeStartingTime">The range starting time in millis.</param>
    /// <param name="rangeEndingTime">The range ending time in millis.</param>
    public DailyCalendar(ICalendar? baseCalendar, string rangeStartingTime, string rangeEndingTime) : base(baseCalendar)
    {
        SetTimeRange(rangeStartingTime, rangeEndingTime);
    }
M
Marko Lahma 已提交
164

165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
    /// <summary>
    /// Create a <see cref="DailyCalendar" /> with a time range defined by the
    /// specified values and no baseCalendar. Values are subject to
    /// the following validations:
    /// <ul>
    ///     <li>
    ///         Hours must be in the range 0-23 and are expressed using military
    ///		    (24-hour) time.
    ///     </li>
    ///		<li>Minutes must be in the range 0-59</li>
    ///		<li>Seconds must be in the range 0-59</li>
    ///		<li>Milliseconds must be in the range 0-999</li>
    ///		<li>
    ///         The time range starting time must be before the time range ending
    ///		    time. Note this means that a time range may not cross daily
    ///		    boundaries (10PM - 2AM)
    ///     </li>
    /// </ul>
    /// </summary>
    /// <param name="rangeStartingHourOfDay">The range starting hour of day.</param>
    /// <param name="rangeStartingMinute">The range starting minute.</param>
    /// <param name="rangeStartingSecond">The range starting second.</param>
    /// <param name="rangeStartingMillis">The range starting millis.</param>
    /// <param name="rangeEndingHourOfDay">The range ending hour of day.</param>
    /// <param name="rangeEndingMinute">The range ending minute.</param>
    /// <param name="rangeEndingSecond">The range ending second.</param>
    /// <param name="rangeEndingMillis">The range ending millis.</param>
    public DailyCalendar(int rangeStartingHourOfDay,
        int rangeStartingMinute,
        int rangeStartingSecond,
        int rangeStartingMillis,
        int rangeEndingHourOfDay,
        int rangeEndingMinute,
        int rangeEndingSecond,
        int rangeEndingMillis)
    {
        SetTimeRange(rangeStartingHourOfDay,
            rangeStartingMinute,
            rangeStartingSecond,
            rangeStartingMillis,
            rangeEndingHourOfDay,
            rangeEndingMinute,
            rangeEndingSecond,
            rangeEndingMillis);
    }
M
Marko Lahma 已提交
210

211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
    /// <summary>
    /// Create a <see cref="DailyCalendar"/> with a time range defined by the
    /// specified values and the specified <paramref name="baseCalendar"/>. Values are
    /// subject to the following validations:
    /// <ul>
    /// 		<li>
    /// Hours must be in the range 0-23 and are expressed using military
    /// (24-hour) time.
    /// </li>
    /// 		<li>Minutes must be in the range 0-59</li>
    /// 		<li>Seconds must be in the range 0-59</li>
    /// 		<li>Milliseconds must be in the range 0-999</li>
    /// 		<li>
    /// The time range starting time must be before the time range ending
    /// time. Note this means that a time range may not cross daily
    /// boundaries (10PM - 2AM)
    /// </li>
    /// 	</ul>
    /// </summary>
    /// <param name="baseCalendar">The base calendar for this calendar instance see BaseCalendar for more
    /// information on base calendar functionality.</param>
    /// <param name="rangeStartingHourOfDay">The range starting hour of day.</param>
    /// <param name="rangeStartingMinute">The range starting minute.</param>
    /// <param name="rangeStartingSecond">The range starting second.</param>
    /// <param name="rangeStartingMillis">The range starting millis.</param>
    /// <param name="rangeEndingHourOfDay">The range ending hour of day.</param>
    /// <param name="rangeEndingMinute">The range ending minute.</param>
    /// <param name="rangeEndingSecond">The range ending second.</param>
    /// <param name="rangeEndingMillis">The range ending millis.</param>
    public DailyCalendar(ICalendar baseCalendar,
        int rangeStartingHourOfDay,
        int rangeStartingMinute,
        int rangeStartingSecond,
        int rangeStartingMillis,
        int rangeEndingHourOfDay,
        int rangeEndingMinute,
        int rangeEndingSecond,
        int rangeEndingMillis) : base(baseCalendar)
    {
        SetTimeRange(rangeStartingHourOfDay,
            rangeStartingMinute,
            rangeStartingSecond,
            rangeStartingMillis,
            rangeEndingHourOfDay,
            rangeEndingMinute,
            rangeEndingSecond,
            rangeEndingMillis);
    }
M
Marko Lahma 已提交
259

260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
    /// <summary>
    /// Create a <see cref="DailyCalendar" /> with a time range defined by the
    ///	specified <see cref="DateTime" />s and no
    ///	baseCalendar. The Calendars are subject to the following
    ///	considerations:
    ///	<ul>
    ///     <li>
    ///         Only the time-of-day fields of the specified Calendars will be
    ///		    used (the date fields will be ignored)
    ///     </li>
    ///		<li>
    ///         The starting time must be before the ending time of the defined
    ///		    time range. Note this means that a time range may not cross
    ///		    daily boundaries (10PM - 2AM). <i>(because only time fields are
    ///		    are used, it is possible for two Calendars to represent a valid
    ///		    time range and
    ///		    <c>rangeStartingCalendar.after(rangeEndingCalendar) ==  true</c>)
    ///			</i>
    ///     </li>
    /// </ul>
    /// </summary>
    /// <param name="rangeStartingCalendarUtc">The range starting calendar.</param>
    /// <param name="rangeEndingCalendarUtc">The range ending calendar.</param>
    public DailyCalendar(DateTime rangeStartingCalendarUtc, DateTime rangeEndingCalendarUtc)
    {
        SetTimeRange(rangeStartingCalendarUtc, rangeEndingCalendarUtc);
    }
M
Marko Lahma 已提交
287

288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
    /// <summary>
    /// Create a <see cref="DailyCalendar"/> with a time range defined by the
    /// specified <see cref="DateTime"/>s and the specified
    /// <paramref name="baseCalendar"/>. The Calendars are subject to the following
    /// considerations:
    /// <ul>
    /// 		<li>
    /// Only the time-of-day fields of the specified Calendars will be
    /// used (the date fields will be ignored)
    /// </li>
    /// 		<li>
    /// The starting time must be before the ending time of the defined
    /// time range. Note this means that a time range may not cross
    /// daily boundaries (10PM - 2AM). <i>(because only time fields are
    /// are used, it is possible for two Calendars to represent a valid
    /// time range and
    /// <c>rangeStartingCalendarUtc > rangeEndingCalendarUtc == true</c>)</i>
    /// 		</li>
    /// 	</ul>
    /// </summary>
    /// <param name="baseCalendar">The base calendar for this calendar instance see BaseCalendar for more
    /// information on base calendar functionality.</param>
    /// <param name="rangeStartingCalendarUtc">The range starting calendar.</param>
    /// <param name="rangeEndingCalendarUtc">The range ending calendar.</param>
    public DailyCalendar(ICalendar baseCalendar,
        DateTime rangeStartingCalendarUtc,
        DateTime rangeEndingCalendarUtc) : base(baseCalendar)
    {
        SetTimeRange(rangeStartingCalendarUtc, rangeEndingCalendarUtc);
    }
M
Marko Lahma 已提交
318

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
    /// <summary>
    /// Create a <see cref="DailyCalendar" /> with a time range defined by the
    /// specified values and no baseCalendar. The values are
    ///	subject to the following considerations:
    ///	<ul>
    ///     <li>
    ///         Only the time-of-day portion of the specified values will be
    ///		    used
    ///     </li>
    ///		<li>
    ///         The starting time must be before the ending time of the defined
    ///		    time range. Note this means that a time range may not cross
    ///		    daily boundaries (10PM - 2AM). <i>(because only time value are
    ///		    are used, it is possible for the two values to represent a valid
    ///		    time range and <c>rangeStartingTime &gt; rangeEndingTime</c>)</i>
    ///     </li>
    /// </ul>
    /// </summary>
    /// <param name="rangeStartingTimeInMillis">The range starting time in millis.</param>
    /// <param name="rangeEndingTimeInMillis">The range ending time in millis.</param>
    public DailyCalendar(long rangeStartingTimeInMillis, long rangeEndingTimeInMillis)
    {
        SetTimeRange(rangeStartingTimeInMillis, rangeEndingTimeInMillis);
    }
M
Marko Lahma 已提交
343

344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
    /// <summary>
    /// Create a <see cref="DailyCalendar"/> with a time range defined by the
    /// specified values and the specified <paramref name="baseCalendar"/>. The values
    /// are subject to the following considerations:
    /// <ul>
    /// 		<li>
    /// Only the time-of-day portion of the specified values will be
    /// used
    /// </li>
    /// 		<li>
    /// The starting time must be before the ending time of the defined
    /// time range. Note this means that a time range may not cross
    /// daily boundaries (10PM - 2AM). <i>(because only time value are
    /// are used, it is possible for the two values to represent a valid
    /// time range and <c>rangeStartingTime &gt; rangeEndingTime</c>)</i>
    /// 		</li>
    /// 	</ul>
    /// </summary>
    /// <param name="baseCalendar">The base calendar for this calendar instance see BaseCalendar for more
    /// information on base calendar functionality.</param>
    /// <param name="rangeStartingTimeInMillis">The range starting time in millis.</param>
    /// <param name="rangeEndingTimeInMillis">The range ending time in millis.</param>
    public DailyCalendar(ICalendar baseCalendar,
        long rangeStartingTimeInMillis,
        long rangeEndingTimeInMillis) : base(baseCalendar)
    {
        SetTimeRange(rangeStartingTimeInMillis,
            rangeEndingTimeInMillis);
    }

    /// <summary>
    /// Serialization constructor.
    /// </summary>
    /// <param name="info"></param>
    /// <param name="context"></param>
379
    private DailyCalendar(SerializationInfo info, StreamingContext context) : base(info, context)
380 381 382
    {
        int version;
        try
M
Marko Lahma 已提交
383
        {
384
            version = info.GetInt32("version");
M
Marko Lahma 已提交
385
        }
386
        catch
M
Marko Lahma 已提交
387
        {
388
            version = 0;
M
Marko Lahma 已提交
389 390
        }

391
        switch (version)
392
        {
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
            case 0:
            case 1:
                rangeStartingHourOfDay = info.GetInt32("rangeStartingHourOfDay");
                rangeStartingMinute = info.GetInt32("rangeStartingMinute");
                rangeStartingSecond = info.GetInt32("rangeStartingSecond");
                rangeStartingMillis = info.GetInt32("rangeStartingMillis");

                rangeEndingHourOfDay = info.GetInt32("rangeEndingHourOfDay");
                rangeEndingMinute = info.GetInt32("rangeEndingMinute");
                rangeEndingSecond = info.GetInt32("rangeEndingSecond");
                rangeEndingMillis = info.GetInt32("rangeEndingMillis");

                InvertTimeRange = info.GetBoolean("invertTimeRange");
                break;
            default:
                ThrowHelper.ThrowNotSupportedException("Unknown serialization version");
                break;
410
        }
411
    }
412

413 414 415 416 417 418 419 420 421 422
    [System.Security.SecurityCritical]
    public override void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        base.GetObjectData(info, context);

        info.AddValue("version", 1);
        info.AddValue("rangeStartingHourOfDay", rangeStartingHourOfDay);
        info.AddValue("rangeStartingMinute", rangeStartingMinute);
        info.AddValue("rangeStartingSecond", rangeStartingSecond);
        info.AddValue("rangeStartingMillis", rangeStartingMillis);
423

424 425 426 427
        info.AddValue("rangeEndingHourOfDay", rangeEndingHourOfDay);
        info.AddValue("rangeEndingMinute", rangeEndingMinute);
        info.AddValue("rangeEndingSecond", rangeEndingSecond);
        info.AddValue("rangeEndingMillis", rangeEndingMillis);
428

429 430
        info.AddValue("invertTimeRange", InvertTimeRange);
    }
431

432 433 434 435 436 437 438 439 440 441 442 443
    /// <summary>
    /// Determine whether the given time  is 'included' by the
    /// Calendar.
    /// </summary>
    /// <param name="timeUtc"></param>
    /// <returns></returns>
    public override bool IsTimeIncluded(DateTimeOffset timeUtc)
    {
        if (CalendarBase != null
            && CalendarBase.IsTimeIncluded(timeUtc) == false)
        {
            return false;
444 445
        }

446 447 448 449 450 451 452 453
        //Before we start, apply the correct timezone offsets.
        timeUtc = TimeZoneUtil.ConvertTime(timeUtc, TimeZone);

        DateTimeOffset startOfDayInMillis = GetStartOfDay(timeUtc);
        DateTimeOffset endOfDayInMillis = GetEndOfDay(timeUtc);
        DateTimeOffset timeRangeStartingTimeInMillis = GetTimeRangeStartingTimeUtc(timeUtc);
        DateTimeOffset timeRangeEndingTimeInMillis = GetTimeRangeEndingTimeUtc(timeUtc);
        if (!InvertTimeRange)
M
Marko Lahma 已提交
454
        {
455 456 457 458
            if (timeUtc >= startOfDayInMillis &&
                timeUtc < timeRangeStartingTimeInMillis ||
                timeUtc > timeRangeEndingTimeInMillis &&
                timeUtc <= endOfDayInMillis)
M
Marko Lahma 已提交
459
            {
460
                return true;
M
Marko Lahma 已提交
461
            }
462 463 464 465 466 467 468 469 470
            return false;
        }
        if (timeUtc >= timeRangeStartingTimeInMillis &&
            timeUtc <= timeRangeEndingTimeInMillis)
        {
            return true;
        }
        return false;
    }
M
Marko Lahma 已提交
471

472 473 474 475 476 477 478 479 480 481 482
    /// <summary>
    /// Determine the next time (in milliseconds) that is 'included' by the
    /// Calendar after the given time. Return the original value if timeStamp is
    /// included. Return 0 if all days are excluded.
    /// </summary>
    /// <param name="timeUtc"></param>
    /// <returns></returns>
    /// <seealso cref="ICalendar.GetNextIncludedTimeUtc"/>
    public override DateTimeOffset GetNextIncludedTimeUtc(DateTimeOffset timeUtc)
    {
        DateTimeOffset nextIncludedTime = timeUtc.AddMilliseconds(OneMillis);
483

484 485
        while (!IsTimeIncluded(nextIncludedTime))
        {
M
Marko Lahma 已提交
486
            if (!InvertTimeRange)
M
Marko Lahma 已提交
487
            {
488 489 490 491 492 493 494 495 496 497
                //If the time is in a range excluded by this calendar, we can
                // move to the end of the excluded time range and continue
                // testing from there. Otherwise, if nextIncludedTime is
                // excluded by the baseCalendar, ask it the next time it
                // includes and begin testing from there. Failing this, add one
                // millisecond and continue testing.
                if (nextIncludedTime >=
                    GetTimeRangeStartingTimeUtc(nextIncludedTime) &&
                    nextIncludedTime <=
                    GetTimeRangeEndingTimeUtc(nextIncludedTime))
M
Marko Lahma 已提交
498
                {
499 500 501 502 503 504 505 506 507 508 509 510
                    nextIncludedTime =
                        GetTimeRangeEndingTimeUtc(nextIncludedTime).AddMilliseconds(OneMillis);
                }
                else if (CalendarBase != null &&
                         !CalendarBase.IsTimeIncluded(nextIncludedTime))
                {
                    nextIncludedTime =
                        CalendarBase.GetNextIncludedTimeUtc(nextIncludedTime);
                }
                else
                {
                    nextIncludedTime = nextIncludedTime.AddMilliseconds(1);
M
Marko Lahma 已提交
511 512
                }
            }
513
            else
M
Marko Lahma 已提交
514
            {
515 516 517 518 519 520 521 522 523 524 525 526 527 528
                //If the time is in a range excluded by this calendar, we can
                // move to the end of the excluded time range and continue
                // testing from there. Otherwise, if nextIncludedTime is
                // excluded by the baseCalendar, ask it the next time it
                // includes and begin testing from there. Failing this, add one
                // millisecond and continue testing.
                if (nextIncludedTime <
                    GetTimeRangeStartingTimeUtc(nextIncludedTime))
                {
                    nextIncludedTime =
                        GetTimeRangeStartingTimeUtc(nextIncludedTime);
                }
                else if (nextIncludedTime >
                         GetTimeRangeEndingTimeUtc(nextIncludedTime))
M
Marko Lahma 已提交
529
                {
530 531 532 533 534 535 536 537 538
                    //(move to start of next day)
                    nextIncludedTime = GetEndOfDay(nextIncludedTime);
                    nextIncludedTime = nextIncludedTime.AddMilliseconds(1);
                }
                else if (CalendarBase != null &&
                         !CalendarBase.IsTimeIncluded(nextIncludedTime))
                {
                    nextIncludedTime =
                        CalendarBase.GetNextIncludedTimeUtc(nextIncludedTime);
M
Marko Lahma 已提交
539 540 541
                }
                else
                {
542
                    nextIncludedTime = nextIncludedTime.AddMilliseconds(1);
M
Marko Lahma 已提交
543 544 545 546
                }
            }
        }

547 548
        return nextIncludedTime;
    }
M
Marko Lahma 已提交
549

550 551 552
    public override ICalendar Clone()
    {
        var clone = new DailyCalendar(CalendarBase, RangeStartingTime, RangeEndingTime)
M
Marko Lahma 已提交
553
        {
554 555 556 557 558
            InvertTimeRange = InvertTimeRange
        };
        CloneFields(clone);
        return clone;
    }
M
Marko Lahma 已提交
559

560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
    /// <summary>
    /// Returns the start time of the time range of the day
    /// specified in <paramref name="timeUtc" />.
    /// </summary>
    /// <returns>
    ///     a DateTime representing the start time of the
    ///     time range for the specified date.
    /// </returns>
    public DateTimeOffset GetTimeRangeStartingTimeUtc(DateTimeOffset timeUtc)
    {
        DateTimeOffset rangeStartingTime = new DateTimeOffset(timeUtc.Year, timeUtc.Month, timeUtc.Day,
            rangeStartingHourOfDay, rangeStartingMinute,
            rangeStartingSecond, rangeStartingMillis, timeUtc.Offset);
        return rangeStartingTime;
    }

    /// <summary>
    /// Returns the end time of the time range of the day
    /// specified in <paramref name="timeUtc" />
    /// </summary>
    /// <returns>
    /// A DateTime representing the end time of the
    /// time range for the specified date.
    /// </returns>
    public DateTimeOffset GetTimeRangeEndingTimeUtc(DateTimeOffset timeUtc)
    {
        DateTimeOffset rangeEndingTime = new DateTimeOffset(timeUtc.Year, timeUtc.Month, timeUtc.Day,
            rangeEndingHourOfDay, rangeEndingMinute,
            rangeEndingSecond, rangeEndingMillis, timeUtc.Offset);
        return rangeEndingTime;
    }
M
Marko Lahma 已提交
591

592 593 594 595 596 597
    /// <summary>
    /// Indicates whether the time range represents an inverted time range (see
    /// class description).
    /// </summary>
    /// <value><c>true</c> if invert time range; otherwise, <c>false</c>.</value>
    public bool InvertTimeRange { get; set; }
M
Marko Lahma 已提交
598

599 600
    public string RangeStartingTime => FormatTimeRange(rangeStartingHourOfDay, rangeStartingMinute, rangeStartingSecond, rangeStartingMillis);
    public string RangeEndingTime => FormatTimeRange(rangeEndingHourOfDay, rangeEndingMinute, rangeEndingSecond, rangeEndingMillis);
601

602 603 604 605
    private static string FormatTimeRange(int hourOfDay, int minute, int seconds, int milliseconds)
    {
        return $"{hourOfDay.ToString(TwoDigitFormat, CultureInfo.InvariantCulture)}:{minute.ToString(TwoDigitFormat, CultureInfo.InvariantCulture)}:{seconds.ToString(TwoDigitFormat, CultureInfo.InvariantCulture)}:{milliseconds.ToString(ThreeDigitFormat, CultureInfo.InvariantCulture)}";
    }
606

607 608 609 610 611 612 613 614 615 616 617
    /// <summary>
    /// Returns a <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
    /// </summary>
    /// <returns>
    /// A <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
    /// </returns>
    public override string ToString()
    {
        StringBuilder buffer = new StringBuilder();
        buffer.Append("base calendar: [");
        if (CalendarBase != null)
M
Marko Lahma 已提交
618
        {
619
            buffer.Append(CalendarBase);
M
Marko Lahma 已提交
620
        }
621
        else
M
Marko Lahma 已提交
622
        {
623 624
            buffer.Append("null");
        }
M
Marko Lahma 已提交
625

626 627 628 629 630 631 632
        buffer.Append("], time range: '");
        buffer.Append(RangeStartingTime);
        buffer.Append(" - ");
        buffer.Append(RangeEndingTime);
        buffer.AppendFormat("', inverted: {0}", InvertTimeRange);
        return buffer.ToString();
    }
M
Marko Lahma 已提交
633

634 635 636 637 638 639 640 641 642 643 644
    /// <summary>
    /// Sets the time range for the <see cref="DailyCalendar" /> to the times
    /// represented in the specified Strings.
    /// </summary>
    /// <param name="rangeStartingTimeString">The range starting time string.</param>
    /// <param name="rangeEndingTimeString">The range ending time string.</param>
    public void SetTimeRange(string rangeStartingTimeString,
        string rangeEndingTimeString)
    {
        int rangeStartingSecond;
        int rangeStartingMillis;
M
Marko Lahma 已提交
645

646 647
        int rangeEndingSecond;
        int rangeEndingMillis;
M
Marko Lahma 已提交
648

649
        var rangeStartingTime = rangeStartingTimeString.Split(Colon);
M
Marko Lahma 已提交
650

651 652 653 654
        if (rangeStartingTime.Length < 2 || rangeStartingTime.Length > 4)
        {
            ThrowHelper.ThrowArgumentException($"Invalid time string '{rangeStartingTimeString}'");
        }
M
Marko Lahma 已提交
655

656 657
        int rangeStartingHourOfDay = Convert.ToInt32(rangeStartingTime[0], CultureInfo.InvariantCulture);
        int rangeStartingMinute = Convert.ToInt32(rangeStartingTime[1], CultureInfo.InvariantCulture);
M
Marko Lahma 已提交
658

659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
        if (rangeStartingTime.Length > 2)
        {
            rangeStartingSecond = Convert.ToInt32(rangeStartingTime[2], CultureInfo.InvariantCulture);
        }
        else
        {
            rangeStartingSecond = 0;
        }
        if (rangeStartingTime.Length == 4)
        {
            rangeStartingMillis = Convert.ToInt32(rangeStartingTime[3], CultureInfo.InvariantCulture);
        }
        else
        {
            rangeStartingMillis = 0;
        }
M
Marko Lahma 已提交
675

676
        var rangeEndingTime = rangeEndingTimeString.Split(Colon);
M
Marko Lahma 已提交
677

678 679 680
        if (rangeEndingTime.Length < 2 || rangeEndingTime.Length > 4)
        {
            ThrowHelper.ThrowArgumentException($"Invalid time string '{rangeEndingTimeString}'");
M
Marko Lahma 已提交
681 682
        }

683 684 685
        int rangeEndingHourOfDay = Convert.ToInt32(rangeEndingTime[0], CultureInfo.InvariantCulture);
        int rangeEndingMinute = Convert.ToInt32(rangeEndingTime[1], CultureInfo.InvariantCulture);
        if (rangeEndingTime.Length > 2)
M
Marko Lahma 已提交
686
        {
687
            rangeEndingSecond = Convert.ToInt32(rangeEndingTime[2], CultureInfo.InvariantCulture);
M
Marko Lahma 已提交
688
        }
689
        else
M
Marko Lahma 已提交
690
        {
691
            rangeEndingSecond = 0;
M
Marko Lahma 已提交
692
        }
693
        if (rangeEndingTime.Length == 4)
M
Marko Lahma 已提交
694
        {
695
            rangeEndingMillis = Convert.ToInt32(rangeEndingTime[3], CultureInfo.InvariantCulture);
M
Marko Lahma 已提交
696
        }
697
        else
M
Marko Lahma 已提交
698
        {
699
            rangeEndingMillis = 0;
M
Marko Lahma 已提交
700 701
        }

702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
        SetTimeRange(rangeStartingHourOfDay,
            rangeStartingMinute,
            rangeStartingSecond,
            rangeStartingMillis,
            rangeEndingHourOfDay,
            rangeEndingMinute,
            rangeEndingSecond,
            rangeEndingMillis);
    }

    /// <summary>
    /// Sets the time range for the <see cref="DailyCalendar" /> to the times
    /// represented in the specified values.
    /// </summary>
    /// <param name="rangeStartingHourOfDay">The range starting hour of day.</param>
    /// <param name="rangeStartingMinute">The range starting minute.</param>
    /// <param name="rangeStartingSecond">The range starting second.</param>
    /// <param name="rangeStartingMillis">The range starting millis.</param>
    /// <param name="rangeEndingHourOfDay">The range ending hour of day.</param>
    /// <param name="rangeEndingMinute">The range ending minute.</param>
    /// <param name="rangeEndingSecond">The range ending second.</param>
    /// <param name="rangeEndingMillis">The range ending millis.</param>
    public void SetTimeRange(int rangeStartingHourOfDay,
        int rangeStartingMinute,
        int rangeStartingSecond,
        int rangeStartingMillis,
        int rangeEndingHourOfDay,
        int rangeEndingMinute,
        int rangeEndingSecond,
        int rangeEndingMillis)
    {
        Validate(rangeStartingHourOfDay,
            rangeStartingMinute,
            rangeStartingSecond,
            rangeStartingMillis);

        Validate(rangeEndingHourOfDay,
            rangeEndingMinute,
            rangeEndingSecond,
            rangeEndingMillis);

        DateTimeOffset startCal = SystemTime.UtcNow();
        startCal =
            new DateTimeOffset(startCal.Year, startCal.Month, startCal.Day, rangeStartingHourOfDay, rangeStartingMinute,
                rangeStartingSecond, rangeStartingMillis, TimeSpan.Zero);

        DateTimeOffset endCal = SystemTime.UtcNow();
        endCal =
            new DateTimeOffset(endCal.Year, endCal.Month, endCal.Day, rangeEndingHourOfDay, rangeEndingMinute,
                rangeEndingSecond, rangeEndingMillis, TimeSpan.Zero);

        if (!(startCal < endCal))
M
Marko Lahma 已提交
754
        {
755
            ThrowHelper.ThrowArgumentException($"{InvalidTimeRange}{rangeStartingHourOfDay}:{rangeStartingMinute}:{rangeStartingSecond}:{rangeStartingMillis}{Separator}{rangeEndingHourOfDay}:{rangeEndingMinute}:{rangeEndingSecond}:{rangeEndingMillis}");
M
Marko Lahma 已提交
756 757
        }

758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
        this.rangeStartingHourOfDay = rangeStartingHourOfDay;
        this.rangeStartingMinute = rangeStartingMinute;
        this.rangeStartingSecond = rangeStartingSecond;
        this.rangeStartingMillis = rangeStartingMillis;
        this.rangeEndingHourOfDay = rangeEndingHourOfDay;
        this.rangeEndingMinute = rangeEndingMinute;
        this.rangeEndingSecond = rangeEndingSecond;
        this.rangeEndingMillis = rangeEndingMillis;
    }

    /// <summary>
    /// Sets the time range for the <see cref="DailyCalendar" /> to the times
    /// represented in the specified <see cref="DateTime" />s.
    /// </summary>
    /// <param name="rangeStartingCalendarUtc">The range starting calendar.</param>
    /// <param name="rangeEndingCalendarUtc">The range ending calendar.</param>
    public void SetTimeRange(DateTime rangeStartingCalendarUtc,
        DateTime rangeEndingCalendarUtc)
    {
        SetTimeRange(
            rangeStartingCalendarUtc.Hour,
            rangeStartingCalendarUtc.Minute,
            rangeStartingCalendarUtc.Second,
            rangeStartingCalendarUtc.Millisecond,
            rangeEndingCalendarUtc.Hour,
            rangeEndingCalendarUtc.Minute,
            rangeEndingCalendarUtc.Second,
            rangeEndingCalendarUtc.Millisecond);
    }

    /// <summary>
    /// Sets the time range for the <see cref="DailyCalendar" /> to the times
    /// represented in the specified values.
    /// </summary>
    /// <param name="rangeStartingTime">The range starting time.</param>
    /// <param name="rangeEndingTime">The range ending time.</param>
    public void SetTimeRange(long rangeStartingTime,
        long rangeEndingTime)
    {
        SetTimeRange(new DateTime(rangeStartingTime), new DateTime(rangeEndingTime));
    }

    /// <summary>
    /// Gets the start of day, practically zeroes time part.
    /// </summary>
    /// <param name="time">The time.</param>
    /// <returns></returns>
    private static DateTimeOffset GetStartOfDay(DateTimeOffset time)
    {
807
        return new DateTimeOffset(new DateTime(time.Year, time.Month, time.Day, 0, 0, 0, 0), time.Offset);
808 809 810 811 812 813 814 815 816
    }

    /// <summary>
    /// Gets the end of day, practically sets time parts to maximum allowed values.
    /// </summary>
    /// <param name="time">The time.</param>
    /// <returns></returns>
    private static DateTimeOffset GetEndOfDay(DateTimeOffset time)
    {
817
        return new DateTimeOffset(new DateTime(time.Year, time.Month, time.Day, 23, 59, 59, 999), time.Offset);
818 819 820 821 822 823 824 825 826 827 828 829
    }

    /// <summary>
    /// Checks the specified values for validity as a set of time values.
    /// </summary>
    /// <param name="hourOfDay">The hour of day.</param>
    /// <param name="minute">The minute.</param>
    /// <param name="second">The second.</param>
    /// <param name="millis">The millis.</param>
    private static void Validate(int hourOfDay, int minute, int second, int millis)
    {
        if (hourOfDay < 0 || hourOfDay > 23)
M
Marko Lahma 已提交
830
        {
831
            ThrowHelper.ThrowArgumentException(InvalidHourOfDay + hourOfDay);
M
Marko Lahma 已提交
832
        }
833
        if (minute < 0 || minute > 59)
M
Marko Lahma 已提交
834
        {
835
            ThrowHelper.ThrowArgumentException(InvalidMinute + minute);
M
Marko Lahma 已提交
836
        }
837
        if (second < 0 || second > 59)
M
Marko Lahma 已提交
838
        {
839 840 841 842 843
            ThrowHelper.ThrowArgumentException(InvalidSecond + second);
        }
        if (millis < 0 || millis > 999)
        {
            ThrowHelper.ThrowArgumentException(InvalidMillis + millis);
M
Marko Lahma 已提交
844
        }
845 846 847 848 849 850 851 852 853
    }

    public override int GetHashCode()
    {
        int baseHash = 0;
        if (CalendarBase != null)
            baseHash = CalendarBase.GetHashCode();

        return rangeStartingHourOfDay.GetHashCode() + rangeEndingHourOfDay.GetHashCode() +
M
Marko Lahma 已提交
854 855 856 857
               2 * (rangeStartingMinute.GetHashCode() + rangeEndingMinute.GetHashCode()) +
               3 * (rangeStartingSecond.GetHashCode() + rangeEndingSecond.GetHashCode()) +
               4 * (rangeStartingMillis.GetHashCode() + rangeEndingMillis.GetHashCode())
               + 5 * baseHash;
858
    }
M
Marko Lahma 已提交
859

860 861 862
    public bool Equals(DailyCalendar obj)
    {
        if (obj == null)
M
Marko Lahma 已提交
863
        {
864
            return false;
M
Marko Lahma 已提交
865
        }
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
        bool baseEqual = CalendarBase == null || CalendarBase.Equals(obj.CalendarBase);

        return baseEqual && InvertTimeRange == obj.InvertTimeRange &&
               rangeStartingHourOfDay == obj.rangeStartingHourOfDay &&
               rangeStartingMinute == obj.rangeStartingMinute &&
               rangeStartingSecond == obj.rangeStartingSecond &&
               rangeStartingMillis == obj.rangeStartingMillis &&
               rangeEndingHourOfDay == obj.rangeEndingHourOfDay &&
               rangeEndingMinute == obj.rangeEndingMinute &&
               rangeEndingSecond == obj.rangeEndingSecond &&
               rangeEndingMillis == obj.rangeEndingMillis;
    }

    public override bool Equals(object? obj)
    {
        if (!(obj is DailyCalendar))
            return false;
        return Equals((DailyCalendar) obj);
M
Marko Lahma 已提交
884
    }
M
Marko Lahma 已提交
885
}