Esempio n. 1
0
        public override DateTime Next(DateTime time, out bool changed)
        {
            changed = false;

            if (Values.Count < 1)
            {
                return time;
            }
            if (Type == CGtd.DATES_TYPE_EACH)
            {
                return time.AddMinutes(Values[0]);
            }
            if (Type == CGtd.DATES_TYPE_WHEN)
            {
                int idx = time.Minute;
                int tmp = NextValue(idx, changed);
                if (tmp > 0)
                {
                    return time.AddMinutes(tmp);
                }
                if (tmp < 0)
                {
                    changed = true;
                    return time.AddHours(1).AddMinutes(Values[0] - idx);
                }
            }
            return time;
        }
        public static WeatherLocatioinModel LoadLocationWeatherData(DateTime now, Location location, WeatherData[] locationData)
        {
            var minDate = now.AddMinutes(-90);
            var maxDate = now.AddMinutes(90);

            // погода на текущее время
            var current = locationData.FirstOrDefault(d => d.Date > minDate && d.Date <= maxDate);

            // погода на ближайшие сутки
            var xxx = current != null ? current.Date : now;
            var day = locationData
                        .Where(d => d.Date > xxx && d.Date <= xxx.AddDays(1))
                        .Where(FilterByHours)
                        .OrderBy(d => d.Date)
                        .Take(3)
                        .ToArray();

            // прогноз на несколько дней
            var forecast = locationData
                        .Where(d => d.Date.Date > now.Date)
                        .GroupBy(d => d.Date.Date)
                        .Take(3);

            return new WeatherLocatioinModel
            {
                LocationId = location.Id,
                LocationName = location.DisplayName,
                Now = CreateNowModel(current),
                Today = day.Select(CreateNowModel).ToArray(),
                Forecast = forecast.Select(CreateDayModel).ToArray()
            };
        }
        public static bool CompareDate(DateTime dateToCompare, DateTime date, int minuteTolerance)
        {
            if (!dateToCompare.Equals(date))
            {
                date = date.AddMinutes(minuteTolerance);

                if (!dateToCompare.Equals(date))
                {
                    date = date.AddMinutes(-2 * minuteTolerance);

                    if (!dateToCompare.Equals(date))
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return true;
            }
        }
        /// <summary>
        /// 作者:Beta 
        /// 时间:2014.03.17
        /// 描述:获取样式列表(需求展示)
        /// </summary>
        /// <param name="list"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string GetStudentClassList(List<Model.Eme.BookRequirement> list, DateTime dt)
        {
            var classlist = " select-item";

            if (dt.AddHours(-1) < DateTime.Now)
            {
                if (list.Any(p => p.BookStartTime <= dt && p.BookEndTime >= dt.AddMinutes(30) && p.IsSuccessful))
                {
                    classlist = classlist + " successful";
                }
                else if (list.Any(p => p.BookStartTime <= dt && p.BookEndTime >= dt.AddMinutes(30) && !p.IsSuccessful))
                {
                    classlist = classlist + " pass";
                }
                else
                {
                    classlist = classlist + " unavailable";
                }
            }
            else
            {
                if (list.Any(p => p.BookStartTime <= dt && p.BookEndTime >= dt.AddMinutes(30) && p.IsSuccessful))
                {
                    classlist = classlist + " successful";
                }
                else if (list.Any(p => p.BookStartTime <= dt && p.BookEndTime >= dt.AddMinutes(30) && !p.IsSuccessful))
                {
                    classlist = classlist + " normal oking";
                }
            }
            return classlist;
        }
 public void ReorganizeAdStacks(IDictionary<DateTime,  IDictionary<Guid, IDictionary<Ad, IDictionary<int, long>>>> adDispatchPlans, DateTime currentTime)
 {
     var time = new DateTime(currentTime.Year, currentTime.Month, currentTime.Day, currentTime.Hour, currentTime.Minute, 0);
     if (adDispatchPlans != null && adDispatchPlans.ContainsKey(time.AddMinutes(-1)) && adDispatchPlans.ContainsKey(time.AddMinutes(1)))
     {
         //上一分钟
         var lastMeidaAdPlans = adDispatchPlans[time.AddMinutes(-1)];
         //下一分钟
         var nextMediaAdPlans = adDispatchPlans[time.AddMinutes(1)];
         //轮询处理每个媒体的广告
         foreach (var lastAdMediaAdPlan in lastMeidaAdPlans.AsParallel())
         {
             var mediaId = lastAdMediaAdPlan.Key;
             if (!nextMediaAdPlans.ContainsKey(mediaId))
             {
                 nextMediaAdPlans[mediaId] = new ConcurrentDictionary<Ad, IDictionary<int, long>>();
             }
             //轮询处理该媒体内每个广告
             foreach (var lastAdPlan in lastAdMediaAdPlan.Value)
             {
                 int i = 0;
                 while (lastAdPlan.Value.ContainsKey(i))
                 {
                     if (!nextMediaAdPlans[mediaId].ContainsKey(lastAdPlan.Key))
                     {
                         nextMediaAdPlans[mediaId][lastAdPlan.Key] = new ConcurrentDictionary<int, long>();
                     }
                     //TODO:对于贴片位置定向的情况需要进行处理
                     nextMediaAdPlans[mediaId][lastAdPlan.Key][i + 1] = lastAdPlan.Value[i];
                     i++;
                 }
             }
         }
     }
 }
Esempio n. 6
0
        /// <summary>
        /// Returns the date that is 30 minutes before or after input date if input date minute is 0 or 30. Otherwise it returns next increment to 0 or 30.
        /// </summary>
        /// <param name="date">Date and time.</param>
        /// <param name="forward">Indicates whether to add or subtract minutes.</param>
        /// <returns>New date time.</returns>
        public static DateTime GetNext30Minute(DateTime date, bool forward)
        {
            if (date.Minute == 0 || date.Minute == 30)
                return (date.AddMinutes(forward ? 30 : -30));

            return (date.AddMinutes((forward ? 1 : -1) * Math.Abs(30 - date.Minute)));
        }
        public void UpdatesAfterCorrectPeriodElapses()
        {
            const int periods = 3;
            var periodSpan = Time.OneMinute;
            var reference = new DateTime(2016, 04, 06, 12, 0, 0);
            var referenceUtc = reference.ConvertToUtc(TimeZones.NewYork);
            var timeKeeper = new TimeKeeper(referenceUtc);
            var config = new SubscriptionDataConfig(typeof (TradeBar), Symbols.SPY, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, false, false);
            var security = new Security(SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork), config, new Cash("USD", 0, 0), SymbolProperties.GetDefault("USD"));
            security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));

            var model = new RelativeStandardDeviationVolatilityModel(periodSpan, periods);
            security.VolatilityModel = model;

            var first = new IndicatorDataPoint(reference, 1);
            security.SetMarketPrice(first);

            Assert.AreEqual(0m, model.Volatility);

            const decimal value = 0.471404520791032M; // std of 1,2 is ~0.707 over a mean of 1.5
            var second = new IndicatorDataPoint(reference.AddMinutes(1), 2);
            security.SetMarketPrice(second);
            Assert.AreEqual(value, model.Volatility);

            // update should not be applied since not enough time has passed
            var third = new IndicatorDataPoint(reference.AddMinutes(1.01), 1000);
            security.SetMarketPrice(third);
            Assert.AreEqual(value, model.Volatility);

            var fourth = new IndicatorDataPoint(reference.AddMinutes(2), 3m);
            security.SetMarketPrice(fourth);
            Assert.AreEqual(0.5m, model.Volatility);
        }
Esempio n. 8
0
 // Validates to check if teams in a match are available for a given time
 public bool areTeamsFree(Match m, DateTime startTime)
 {
     // Start time can not be earlier than the tournament stage start time
     if (m.TournamentStage.TimeInterval.StartTime > startTime)
     {
         return false;
     }
     foreach (Team team in m.Teams)
     {
         // Get the time interval for a team and for the parameter date
         TimeInterval timesForDate = team.TimeIntervals.First(x => x.StartTime.Date == startTime.Date);
         // Start time can not be earlier than teams start time and the match can not end later than a teams end time
         if (startTime < timesForDate.StartTime || startTime.AddMinutes(m.Duration) > timesForDate.EndTime)
         {
             return false;
         }
         // Check all the matches for the team
         foreach (Match match in team.Matches)
         {
             if (match.IsScheduled && startTime.AddMinutes(m.Duration * 2) > match.StartTime)
             {
                 DateTime teamBreakDone = match.StartTime.AddMinutes(match.Duration * 2);
                 if (startTime < teamBreakDone)
                 {
                     return false;
                 }
             }
         }
     }
     return true;
 }
        private void InsertObjectBlock()
        {
            _taskExecution1 = _executionHelper.InsertOverrideTaskExecution(_taskDefinitionId);

            _baseDateTime = new DateTime(2016, 1, 1);
            var block1 = _blocksHelper.InsertObjectBlock(_taskDefinitionId, DateTime.UtcNow, Guid.NewGuid().ToString()).ToString();
            _blockExecutionId = _blocksHelper.InsertBlockExecution(_taskExecution1, long.Parse(block1), _baseDateTime.AddMinutes(-20), _baseDateTime.AddMinutes(-20), _baseDateTime.AddMinutes(-25), BlockExecutionStatus.Started);
        }
Esempio n. 10
0
		public DateTime CalcNearestFiveMinTime(DateTime dateIn) {
			dateIn = dateIn.AddMinutes(-2);
			int iMin = 5 * (dateIn.Minute / 5);

			DateTime dateOut = dateIn.AddMinutes(0 - dateIn.Minute).AddMinutes(iMin);

			return dateOut;
		}
Esempio n. 11
0
        /// <summary> Limit a date's resolution. For example, the date <code>1095767411000</code>
        /// (which represents 2004-09-21 13:50:11) will be changed to
        /// <code>1093989600000</code> (2004-09-01 00:00:00) when using
        /// <code>Resolution.MONTH</code>.
        ///
        /// </summary>
        /// <param name="resolution">The desired resolution of the date to be returned
        /// </param>
        /// <returns> the date with all values more precise than <code>resolution</code>
        /// set to 0 or 1, expressed as milliseconds since January 1, 1970, 00:00:00 GMT
        /// </returns>
        public static long Round(long time, Resolution resolution)
        {
            System.Globalization.Calendar cal = new System.Globalization.GregorianCalendar();               // {{Aroush}} do we care about 'cal'

            // protected in JDK's prior to 1.4
            //cal.setTimeInMillis(time);

            System.DateTime dt = new System.DateTime(time);

            if (resolution == Resolution.YEAR)
            {
                dt = dt.AddMonths(1 - dt.Month);
                dt = dt.AddDays(1 - dt.Day);
                dt = dt.AddHours(0 - dt.Hour);
                dt = dt.AddMinutes(0 - dt.Minute);
                dt = dt.AddSeconds(0 - dt.Second);
                dt = dt.AddMilliseconds(0 - dt.Millisecond);
            }
            else if (resolution == Resolution.MONTH)
            {
                dt = dt.AddDays(1 - dt.Day);
                dt = dt.AddHours(0 - dt.Hour);
                dt = dt.AddMinutes(0 - dt.Minute);
                dt = dt.AddSeconds(0 - dt.Second);
                dt = dt.AddMilliseconds(0 - dt.Millisecond);
            }
            else if (resolution == Resolution.DAY)
            {
                dt = dt.AddHours(0 - dt.Hour);
                dt = dt.AddMinutes(0 - dt.Minute);
                dt = dt.AddSeconds(0 - dt.Second);
                dt = dt.AddMilliseconds(0 - dt.Millisecond);
            }
            else if (resolution == Resolution.HOUR)
            {
                dt = dt.AddMinutes(0 - dt.Minute);
                dt = dt.AddSeconds(0 - dt.Second);
                dt = dt.AddMilliseconds(0 - dt.Millisecond);
            }
            else if (resolution == Resolution.MINUTE)
            {
                dt = dt.AddSeconds(0 - dt.Second);
                dt = dt.AddMilliseconds(0 - dt.Millisecond);
            }
            else if (resolution == Resolution.SECOND)
            {
                dt = dt.AddMilliseconds(0 - dt.Millisecond);
            }
            else if (resolution == Resolution.MILLISECOND)
            {
                // don't cut off anything
            }
            else
            {
                throw new System.ArgumentException("unknown resolution " + resolution);
            }
            return(dt.Ticks);
        }
Esempio n. 12
0
        private static DateTime ParseRFC822DateNow(string dateString, DateTime defaultDate)
        {
            bool bolSuccess = false;

            System.DateTime dteParsedDate     = default(System.DateTime);
            int             intLastSpaceIndex = dateString.LastIndexOf(" ");

            // First, try to parse the date with .NET's engine
            try
            {
                // Parse date
                dteParsedDate = System.DateTime.Parse(dateString, DateTimeFormatInfo.InvariantInfo);

                // Set to UTC if GMT or Z timezone info is given
                if (dateString.Substring(intLastSpaceIndex + 1) == "GMT" | dateString.Substring(intLastSpaceIndex + 1) == "Z")
                {
                    dteParsedDate.ToUniversalTime();
                }

                bolSuccess = true;
            }
            catch (Exception)
            {
                // Parsing failed, mark to try it "by hand"
                bolSuccess = false;
            }

            if (!bolSuccess)
            {
                // Try a manual parse now without timezone information
                string strTimezone    = dateString.Substring(intLastSpaceIndex + 1);
                string strReducedDate = dateString.Substring(0, intLastSpaceIndex);

                dteParsedDate = System.DateTime.Parse(strReducedDate, DateTimeFormatInfo.InvariantInfo);

                // Now, calculate UTC based on the given timezone in the date string
                if (strTimezone.StartsWith("+"))
                {
                    // The Timezone is given as a +hhmm string
                    dteParsedDate.AddHours(-int.Parse(strReducedDate.Substring(1, 2)));
                    dteParsedDate.AddMinutes(-int.Parse(strReducedDate.Substring(3)));
                }
                else if (strTimezone.StartsWith("-"))
                {
                    // The Timezone is given as a -hhmm string
                    // The Timezone is given as a +hhmm string
                    dteParsedDate.AddHours(int.Parse(strReducedDate.Substring(1, 2)));
                    dteParsedDate.AddMinutes(int.Parse(strReducedDate.Substring(3)));
                }
                else
                {
                    // The Timezone is given as a named string
                    dteParsedDate = dteParsedDate.AddHours(GetHoursByCode(strTimezone));
                }
            }

            return(dteParsedDate);
        }
Esempio n. 13
0
        // parse "last minute", "next hour"
        private DateTimeResolutionResult ParseRelativeUnit(string text, DateObject referenceTime)
        {
            var ret = new DateTimeResolutionResult();

            var match = Config.RelativeTimeUnitRegex.Match(text);

            if (match.Success)
            {
                var srcUnit = match.Groups["unit"].Value.ToLower();

                var unitStr = Config.UnitMap[srcUnit];

                int swiftValue  = 1;
                var prefixMatch = Config.PastRegex.Match(text);
                if (prefixMatch.Success)
                {
                    swiftValue = -1;
                }

                DateObject beginTime;
                var        endTime = beginTime = referenceTime;

                if (Config.UnitMap.ContainsKey(srcUnit))
                {
                    switch (unitStr)
                    {
                    case "H":
                        beginTime = swiftValue > 0 ? beginTime : referenceTime.AddHours(swiftValue);
                        endTime   = swiftValue > 0 ? referenceTime.AddHours(swiftValue) : endTime;
                        break;

                    case "M":
                        beginTime = swiftValue > 0 ? beginTime : referenceTime.AddMinutes(swiftValue);
                        endTime   = swiftValue > 0 ? referenceTime.AddMinutes(swiftValue) : endTime;
                        break;

                    case "S":
                        beginTime = swiftValue > 0 ? beginTime : referenceTime.AddSeconds(swiftValue);
                        endTime   = swiftValue > 0 ? referenceTime.AddSeconds(swiftValue) : endTime;
                        break;

                    default:
                        return(ret);
                    }

                    ret.Timex =
                        $"({FormatUtil.LuisDate(beginTime)}T{FormatUtil.LuisTime(beginTime)},{FormatUtil.LuisDate(endTime)}T{FormatUtil.LuisTime(endTime)},PT1{unitStr[0]})";
                    ret.FutureValue = ret.PastValue = new Tuple <DateObject, DateObject>(beginTime, endTime);
                    ret.Success     = true;

                    return(ret);
                }
            }

            return(ret);
        }
        private static IEnumerable<Interval<DateTime>> GetDateRangesAllDescendingEndTimes(DateTime date, int count)
        {
            var dateRanges = new Interval<DateTime>[count];

            for (int i = 1; i <= count; i++)
            {
                dateRanges[i - 1] = new Interval<DateTime>(date.AddMinutes(-i), date.AddMinutes(i));
            }

            return new List<Interval<DateTime>>(dateRanges).OrderBy(x => x.Min.Value);
        }
        /// <summary>
        /// 填充没有统计到的时间点
        /// </summary>
        /// <param name="originalDataList"></param>
        /// <returns></returns>
        public IEnumerable<ServiceHostStatMinute> Fill(DateTime startDate, IEnumerable<ServiceHostStatMinute> originalDataList)
        {
            startDate = DateTime.Parse(startDate.ToString("yyyy-MM-dd HH:mm:00"));

            var filledDataList = new List<ServiceHostStatMinute>();
            for (var i = 2; i <= 31; i++)
            {
                var item = originalDataList.FirstOrDefault(m => m.StatTime == startDate.AddMinutes(i * -1)) ?? new ServiceHostStatMinute() { StatTime = startDate.AddMinutes(i * -1) };
                filledDataList.Add(item);
            }
            return filledDataList;
        }
Esempio n. 16
0
        /// <summary>
        /// Asserts that the dates are valid.
        /// </summary>
        public void AssertDateTimes(DateTime expectedDate, DateTime actualDate, int maxMinutesVariance = 1, string message = "")
        {
            if (expectedDate.AddMinutes(maxMinutesVariance) < actualDate)
              {
            Assert.Fail(message);
              }

              if (actualDate < expectedDate.AddMinutes(-maxMinutesVariance))
              {
            Assert.Fail(message);
              }
        }
Esempio n. 17
0
        /// <summary> Limit a date's resolution. For example, the date <c>1095767411000</c>
        /// (which represents 2004-09-21 13:50:11) will be changed to
        /// <c>1093989600000</c> (2004-09-01 00:00:00) when using
        /// <c>Resolution.MONTH</c>.
        ///
        /// </summary>
        /// <param name="time">The time in milliseconds (not ticks).</param>
        /// <param name="resolution">The desired resolution of the date to be returned
        /// </param>
        /// <returns> the date with all values more precise than <c>resolution</c>
        /// set to 0 or 1, expressed as milliseconds since January 1, 1970, 00:00:00 GMT
        /// </returns>
        public static long Round(long time, Resolution resolution)
        {
            var dt = new System.DateTime(time * TimeSpan.TicksPerMillisecond);

            if (resolution == Resolution.YEAR)
            {
                dt = dt.AddMonths(1 - dt.Month);
                dt = dt.AddDays(1 - dt.Day);
                dt = dt.AddHours(0 - dt.Hour);
                dt = dt.AddMinutes(0 - dt.Minute);
                dt = dt.AddSeconds(0 - dt.Second);
                dt = dt.AddMilliseconds(0 - dt.Millisecond);
            }
            else if (resolution == Resolution.MONTH)
            {
                dt = dt.AddDays(1 - dt.Day);
                dt = dt.AddHours(0 - dt.Hour);
                dt = dt.AddMinutes(0 - dt.Minute);
                dt = dt.AddSeconds(0 - dt.Second);
                dt = dt.AddMilliseconds(0 - dt.Millisecond);
            }
            else if (resolution == Resolution.DAY)
            {
                dt = dt.AddHours(0 - dt.Hour);
                dt = dt.AddMinutes(0 - dt.Minute);
                dt = dt.AddSeconds(0 - dt.Second);
                dt = dt.AddMilliseconds(0 - dt.Millisecond);
            }
            else if (resolution == Resolution.HOUR)
            {
                dt = dt.AddMinutes(0 - dt.Minute);
                dt = dt.AddSeconds(0 - dt.Second);
                dt = dt.AddMilliseconds(0 - dt.Millisecond);
            }
            else if (resolution == Resolution.MINUTE)
            {
                dt = dt.AddSeconds(0 - dt.Second);
                dt = dt.AddMilliseconds(0 - dt.Millisecond);
            }
            else if (resolution == Resolution.SECOND)
            {
                dt = dt.AddMilliseconds(0 - dt.Millisecond);
            }
            else if (resolution == Resolution.MILLISECOND)
            {
                // don't cut off anything
            }
            else
            {
                throw new System.ArgumentException("unknown resolution " + resolution);
            }
            return(dt.Ticks);
        }
Esempio n. 18
0
        public void GetMatches_ReturnsCollectionOfScheduleMatches_BetweenLocalTime_AndLastMatchingTime()
        {
            var time = new DateTime(2012, 12, 12, 00, 00, 00, DateTimeKind.Utc);
            var instant = CreateInstant(time);

            var matches = instant.GetMatches(time.AddMinutes(-3)).ToList();

            Assert.Equal(3, matches.Count);
            Assert.Equal(time.AddMinutes(-2), matches[0]);
            Assert.Equal(time.AddMinutes(-1), matches[1]);
            Assert.Equal(time, matches[2]);
        }
    public InProcSessionCacheFixture() {
      _nowUtc = new DateTime(2015, 10, 20, 21, 36, 14, DateTimeKind.Utc);
      _fakeSystemClock = A.Fake<ISystemClock>();
      ConfigureSystemClock_ToReturn(_nowUtc);

      _inProcSessionCache = new InProcSessionCache(_fakeSystemClock);
      _expiredSession = new InProcSession(new SessionId(Guid.NewGuid(), false), A.Dummy<ISession>(), _nowUtc.AddMinutes(-20), TimeSpan.FromMinutes(15));
      _activeSession = new InProcSession(new SessionId(Guid.NewGuid(), false), A.Dummy<ISession>(), _nowUtc.AddMinutes(-3), TimeSpan.FromMinutes(15));
      _inProcSessionCache.Set(_expiredSession);
      _inProcSessionCache.Set(_activeSession);
      _numberOfSessions = 2;
    }
Esempio n. 20
0
		public static long InsertBreak(long emp,DateTime start,int minutes) {
			ClockEvent ce=new ClockEvent();
			ce.ClockStatus=TimeClockStatus.Break;
			ce.EmployeeNum=emp;
			ce.TimeDisplayed1=start;
			ce.TimeEntered1=start;
			ce.TimeDisplayed2=start.AddMinutes(minutes);
			ce.TimeEntered2=start.AddMinutes(minutes);
			ce.ClockEventNum = ClockEvents.Insert(ce);
			ClockEvents.Update(ce);//Updates TimeDisplayed1 because it defaults to now().
			return ce.ClockEventNum;
		}
Esempio n. 21
0
        public NewsReport(string name, string currency, DateTime datetime, int noEntryMinutesPrior, int noEntryMinutesPost, int closeOutMinutesPrior)
        {
            this.name = name;
            this.currency = currency;
            this.datetime = datetime;
            this.noEntryMinutesPrior = noEntryMinutesPrior;
            this.noEntryMinutesPost = noEntryMinutesPost;
            this.closeOutMinutesPrior = closeOutMinutesPrior;

            this.noEntryPriorDateTime = datetime.AddMinutes(-noEntryMinutesPrior);
            this.noEntryPostDateTime = datetime.AddMinutes(noEntryMinutesPost);
            this.closeOutPriorDateTime = datetime.AddMinutes(-closeOutMinutesPrior);

        }
        public void MinutePeriodTest2() {
            // 매 10분마다 수행한다.
            const string PeriodFmt = "0,10,20,30,40,50 * * * *";

            var lastTime = new DateTime(2007, 3, 28, 12, 5, 0);
            var currTime = new DateTime(2007, 3, 28, 12, 9, 55);

            Assert.IsFalse(PeriodTimeFormat.IsExpired(PeriodFmt, lastTime, currTime));
            Assert.IsFalse(PeriodTimeFormat.IsExpired(PeriodFmt, lastTime, currTime.AddSeconds(4)));
            Assert.IsFalse(PeriodTimeFormat.IsExpired(PeriodFmt, lastTime, currTime.AddMinutes(-5)));
            Assert.IsTrue(PeriodTimeFormat.IsExpired(PeriodFmt, lastTime, currTime.AddMinutes(1)));

            Assert.IsTrue(PeriodTimeFormat.IsExpired(PeriodFmt, lastTime.AddMinutes(10), currTime.AddMinutes(11)));
        }
 private static List<KeyValuePair<ServiceTypeModel, Tuple<DateTime, DateTime>>> GetServiceTypesTimeBlocks(DateTime time, IEnumerable<ServiceTypeModel> serviceTypes)
 {
     var result = new List<KeyValuePair<ServiceTypeModel, Tuple<DateTime, DateTime>>>();
     foreach (var type in serviceTypes)
     {
         foreach (var typePhase in type.Phases.OrderBy(x => x.Order))
         {
             var previousPhase = type.Phases.Where(x => x.Order < typePhase.Order);
             var timeOffset = previousPhase.Sum(x => x.DelayInMinutes) + previousPhase.Sum(x => x.DurationInMinutes);
             result.Add(new KeyValuePair<ServiceTypeModel, Tuple<DateTime, DateTime>>(type, new Tuple<DateTime, DateTime>(time.AddMinutes(timeOffset), time.AddMinutes(timeOffset + typePhase.DurationInMinutes))));
         }
     }
     return result;
 }
        public void Should_be_able_to_satisfy_a_stepped_values()
        {
            var field = new CronMinute("5-10/5");

            var control = new DateTime(2011, 01, 01, 0, 0, 0);
            var date = field.SnapForward(control);

            Assert.AreEqual(control.AddMinutes(5), date);
            date = field.SnapForward(date.AddMinutes(1));

            Assert.AreEqual(control.AddMinutes(10), date);
            date = field.SnapForward(date.AddMinutes(1));

            Assert.AreEqual(control.AddMinutes(65), date);
        }
 private EKAlarm ConvertReminder(AppointmentReminder reminder, DateTime startTime)
 {
     switch (reminder)
     {
         case AppointmentReminder.none:
             return EKAlarm.FromDate((NSDate)startTime); ///todo should this be null?
         case AppointmentReminder.five:
             return EKAlarm.FromDate((NSDate)startTime.AddMinutes(-5));
         case AppointmentReminder.fifteen:
             return EKAlarm.FromDate((NSDate)startTime.AddMinutes(-15));
         case AppointmentReminder.thirty:
             return EKAlarm.FromDate((NSDate)startTime.AddMinutes(-30));
     }
     return EKAlarm.FromDate((NSDate)startTime);
 }
Esempio n. 26
0
    public bool AdjustTimeForNextActivity()
    {
        if (RNG.Instance)
        {
            // Adjust the time parameters
            DateTimeForNextActivity.AddHours(
                Mathf.Clamp(RNG.Instance.Range(-MaxTimeHoursVariance, MaxTimeHoursVariance), 0, TimeController.HOURS_IN_DAY - 1));
            DateTimeForNextActivity.AddMinutes(
                Mathf.Clamp(RNG.Instance.Range(-MaxTimeMinutesVariance, MaxTimeMinutesVariance), 0, TimeController.MINUTES_IN_HOUR - 1));
            DateTimeForNextActivity.AddSeconds(
                Mathf.Clamp(RNG.Instance.Range(-MaxTimeSecondsVariance, MaxTimeSecondsVariance), 0, TimeController.SECONDS_IN_MINUTE - 1));

            // ... then update the time controller using the adjusted time
            if (TimeController.Instance)
            {
                TimeController.Instance.SetTimeOfDay(DateTimeForNextActivity, false);
                return(true);
            }

            Debug.LogError("TimeController is not defined in the scene.");
            return(false);
        }

        Debug.LogError("RNG is not defined in the scene.");
        return(false);
    }
Esempio n. 27
0
		//End of address parsing.
		//Date parsing conformant to RFC2822 and accepting RFC822 dates.
		public static System.DateTime ParseAsUniversalDateTime(string input)
		{
			input = Parser.ReplaceTimeZone(input);
			input = Parser.Clean(input);
			input = System.Text.RegularExpressions.Regex.Replace(input,@" +"," ");
			input = System.Text.RegularExpressions.Regex.Replace(input,@"( +: +)|(: +)|( +:)",":");
			if(input.IndexOf(",")!=-1) 
			{
				input = input.Replace(input.Split(',')[0]+", ","");
			}
			string[] parts = input.Split(' ');
			int year = System.Convert.ToInt32(parts[2]);
			if(year<100)
			{
				if(year>49) year += 1900;
				else year += 2000;
			}
			int month = Parser.GetMonth(parts[1]);
			int day = System.Convert.ToInt32(parts[0]);
			string[] dateParts = parts[3].Split(':');
			int hour = System.Convert.ToInt32(dateParts[0]);
			int minute = System.Convert.ToInt32(dateParts[1]);
			int second = 0;
			if(dateParts.Length>2) second = System.Convert.ToInt32(dateParts[2]);
			int offset_hours = System.Convert.ToInt32(parts[4].Substring(0,3));
			int offset_minutes = System.Convert.ToInt32(parts[4].Substring(3,2));
			System.DateTime date = new System.DateTime(year,month,day,hour,minute,second);
			date = date.AddHours(-offset_hours);
			date = date.AddMinutes(-offset_minutes);
			return date;
		}
    void splitMessage()
    {
        javaMessage = jc.GetStatic <string>("text");
        //Debug.Log(javaMessage);
        string[] results;
        results = javaMessage.Split('#');
        if (results[0].Substring(13).Equals("false")) //hasGetrunken=true
        {
            hasDrunk = false;
        }
        else
        {
            hasDrunk = true;
        }
        currentDrunkTime = results[1].Substring(12); //currentTime=16/08/2017 10:10:46

        string formatString = "dd'/'MM'/'yyyy' 'HH':'mm':'ss";
        string sampleData   = results[1].Substring(12);

        currentDrinkDate = System.DateTime.ParseExact(sampleData, formatString, null);

        if (currentDrinkDate.AddMinutes(1) >= System.DateTime.Now)
        {
            connected = true;
        }

        estimatedFillStatus  = int.Parse(results[2].Substring(25)); //estimatedFillStatusInMl=0010
        fillStatusDifference = int.Parse(results[3].Substring(26)); //fillStatusDifferenceInMl=0440
        rawValue             = results[4].Substring(9);             //rawValue=0567
        //GetComponent<TextMesh>().text = connected + "\n" + "hat getrunken: " + hasDrunk + "\n" + "am: " + currentDrunkTime + "\n" + "es befinden sich derzeit ca: " + estimatedFillStatus +
        //"\n" + "getrunken worden ist ca: " + fillStatusDifference + "\n" + "raw: " + rawValue;
    }
Esempio n. 29
0
        /// <summary>
        /// 開始時間変更
        /// </summary>
        /// <param name="index">席番の文字列型</param>
        /// <param name="minusMinutes_string">現在時刻から何分前を開始時刻とするか</param>
        /// <returns>結果を示す文字列</returns>
        public static string TimeChange(string groupIdentifireSeat, string minusMinutes_string)
        {
            int index;

            try {
                index = int.Parse(groupIdentifireSeat);
                if (seats[index] == null)
                {
                    return("SEAT_MUST_BE_USED");
                }
            }
            catch {
                return("SEAT_NOMBER_MUST_BE_A_NOMBER");
            }
            try
            {
                int             timen = int.Parse(minusMinutes_string);
                System.DateTime now   = System.DateTime.Now;
                seats[index].start = now.AddMinutes(-timen);
                return(string.Format("OK_CHANGING_START_TIME_FOR_SEAT{0}_IS_ACCEPTED", groupIdentifireSeat));
            }
            catch {
                return("TIME_MUST_BE_INT");
            }
        }
Esempio n. 30
0
 /// <summary>
 /// Called at the end of each request to clean up stale values.  If the last call was
 /// less that a minute ago, just returns without doing anything.
 /// </summary>
 public static void CleanUp()
 {
     lock (Cards) {
         if (LastCleanup.AddMinutes(1).CompareTo(System.DateTime.Now) > 0)
         {
             return;
         }
         else
         {
             LastCleanup = System.DateTime.Now;
         }
         ArrayList DeleteList = new ArrayList();
         foreach (DictionaryEntry e in Cards)
         {
             if (((SavedCard)e.Value).TimeStamp.CompareTo(System.DateTime.Now.AddHours(-1)) <= 0)
             {
                 DeleteList.Add(e.Key);
             }
         }
         foreach (object i in DeleteList)
         {
             Cards.Remove(i);
         }
     }
 }
Esempio n. 31
0
 public void gamepanel()
 {
     gamemode    = true;
     PanelNumber = 6;
     prevpanel   = Gamepanel;
     PlayTime    = PlayTime.AddMinutes(1);
 }
Esempio n. 32
0
        /// <summary>
        /// 获取时间点
        /// </summary>
        /// <param name="intervalMinute">时间间隔</param>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <param name="getOneDayLastTime">获取一天最后一个时间:23:59:59</param>
        /// <returns></returns>
        public static List <SDateTime> GetTimePoint(int intervalMinute, SDateTime startTime, SDateTime endTime, bool getOneDayLastTime = false)
        {
            List <SDateTime> list = new List <SDateTime>();

            if (startTime >= endTime)
            {
                return(list);
            }

            SDateTime tempTime = startTime;

            list.Add(tempTime);

            while (tempTime < endTime)
            {
                tempTime = tempTime.AddMinutes(intervalMinute);
                list.Add(tempTime);
            }

            list = list.OrderByDescending(t => t).ToList();

            if (getOneDayLastTime)
            {
                list[0] = list[0].AddMinutes(60 * 24).AddSeconds(-1);
            }
            else
            {
                list.RemoveAt(0);
            }

            return(list);
        }
Esempio n. 33
0
        public int CompareTo(object obj)
        {
            if (obj == null)
            {
                return(1);
            }
            if (!(obj is DateTime))
            {
                throw new ArgumentException("Argument is not of type DateTime");
            }
            DateTime dt = (DateTime)obj;

            if (timezone == NoTimezone && dt.timezone != NoTimezone)
            {
                return(0);                      // cannot compare
            }
            if (timezone != NoTimezone && dt.timezone == NoTimezone)
            {
                return(0);                      // cannot compare
            }
            if (timezone == NoTimezone)
            {
                return(myValue.CompareTo(dt.myValue));
            }

            System.DateTime n1 = myValue;
            System.DateTime n2 = dt.myValue;
            n1.AddMinutes(-timezone);
            n2.AddMinutes(-dt.timezone);
            return(n1.CompareTo(n2));
        }
Esempio n. 34
0
        static void SetArray()
        {
            Random r = new Random();
            int year = DateTime.Now.Year;
            int month = DateTime.Now.Month;
            int day = DateTime.Now.Day;

            try
            {
                DateTime openTime = new DateTime(year, month, day);
                int openHour = 10;
                CultureInfo ci = CultureInfo.InvariantCulture;

                //Console.WriteLine(date1.ToString("hh:mm:ss", ci));
                for (int i = 1; i <= 5; i++)
                {
                    using (StreamWriter generate = new StreamWriter("cash" + i + ".txt"))
                    {
                        for (int j = openHour * 60; j <= (openHour + 8) * 60; j += 30)
                        {
                            generate.WriteLine(
                                openTime.AddMinutes((double)j).ToString("HH:mm:ss", ci)
                                + ";" + (r.Next(0, 10)).ToString() + ";");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Houston we have a problem: " + e.Message);
            }
        }
Esempio n. 35
0
		public UpNextTableSource ()
		{
			var sessions = BL.Managers.SessionManager.GetSessions ();
			var now = DateTime.Now;
#if DEBUG
			//TEST: for 'up next' code
			//now = new DateTime(2012,3,28,9,11,0);
			now = new DateTime(2012,2,28,9,11,0);
#endif	
			
			var nowStart = now.AddMinutes ( - (now.Minute % 5)); // round to 5 minutes
//			var happeningNow = from s in sessions
//				where s.Start <= now 
//				&& now < (s.End == DateTime.MinValue ? s.Start.AddHours(1): s.End) 
//				//&& (s.Start.Minute % 10 == 0 || s.Start.Minute % 15 == 0) // fix for short-sessions (which start at :05 after the hour)
//				select s;
//			_upnext = happeningNow.ToList();

			var nextStart = nowStart.AddMinutes (14); // possible fix to (within 30 minutes bug)
			nextStart = nextStart.AddSeconds(-nextStart.Second);
			
			var allUpcoming = from s in sessions
					where s.Start >= nextStart //&& (s.Start.Minute % 10 == 0 || s.Start.Minute % 15 == 0)
					orderby s.Start.Ticks
					group s by s.Start.Ticks into g
					select new { Start = g.Key, Sessions = g };
	
			var upnextGroup = allUpcoming.FirstOrDefault ();
			if (upnextGroup != null) { // conference is over
				upNext = upnextGroup.Sessions.ToList();
				upNextTime = new DateTime(upnextGroup.Start);
			}
		}
Esempio n. 36
0
 private string GetICSString(DateTime date, int duration, string name, string location, string shortDescription)
 {
     var sb = new StringBuilder();
     sb.AppendLine("BEGIN:VCALENDAR");
     sb.AppendLine("VERSION:1.0");
     sb.AppendLine("BEGIN:VEVENT");
     sb.AppendFormat("DTSTART:{0}", GetFormattedTime(date));
     sb.AppendLine();
     sb.AppendFormat("DTEND:{0}", GetFormattedTime(date.AddMinutes(duration)));
     sb.AppendLine();
     sb.AppendFormat("SUMMARY:{0}", name);
     sb.AppendLine();
     sb.AppendFormat("LOCATION:{0}", location);
     sb.AppendLine();
     string description = shortDescription;
     if (description.IsEmpty())
     {
         description = name;
     }
     sb.AppendFormat("DESCRIPTION:{0}", description.Replace(Environment.NewLine, " "));
     sb.AppendLine();
     sb.AppendLine("END:VEVENT");
     sb.AppendLine("END:VCALENDAR");
     return sb.ToString();
 }
Esempio n. 37
0
        public string changeDate(string date, char op, long value)
        {
            int nHoras = (int)value / 60;
            int rHoras = (int)value % 60;
            int nDias = nHoras / 24;
            int nMeses = (int)value / 24;

            //int total_minutes = 4000;
            //int minutes = total_minutes % 60;
            //int total_hours = total_minutes / 60;
            //int horas = total_hours % 24;
            //int total_days = total_hours / 24;
            //int dias = total_days % 365;
            //int anos = total_days / 365;

            //Console.WriteLine(" "+ anos, dias, horas, minutes);

            DateTime dateValue = new DateTime(2016, 11, 17, 14, 0, 0);

            //double[] minutes = { 4000 };
            long minutes = 4000;

            Console.WriteLine(dateValue.AddMinutes(minutes));

            Console.ReadKey();
            return date;
        }
Esempio n. 38
0
        public WeeklyScheduler.WeeklyTime GetDateFromPos(int x, int y)
        {
            int w = this.Width;
            int h = this.Height;
            int leftOffset = 20;
            int topOffset = 20;
            int dayWidth;
            int numOfDays;
            if (renderWeekend)
            {
                numOfDays = 7;
            }
            else
            {
                numOfDays = 5;
            }

            dayWidth = (w - leftOffset) / numOfDays;
            double minHeight = (double)(h - topOffset) / (24d * 60d);
            DateTime dt = new DateTime(0);
            dt = dt.AddMinutes((y - topOffset) / minHeight);
            DayOfWeek dow;
            dow = (DayOfWeek)(int)((x - leftOffset) / dayWidth + 1);
            WeeklyScheduler.WeeklyTime wt = new WeeklyScheduler.WeeklyTime(dow, dt.Hour, dt.Minute);
            return wt;
        }
Esempio n. 39
0
        public string GetJobsToFilesV2(SqlConnection connection, System.DateTime lastrun, string serverName)
        {
            _logger.LogInformation(@"Begin get jobs from " + serverName);
            var ret      = "";
            var workPath = Path.Combine(workDir, serverName);

            try
            {
                if (Directory.Exists(Path.Combine(workPath, "J")))
                {
                    lastrun = lastrun.AddMinutes(-2);
                }
                else
                {
                    ret = "All jobs";
                    Directory.CreateDirectory(Path.Combine(workPath, "J"));
                    lastrun = new System.DateTime(1900, 1, 1);
                }


                var serverConnection = new ServerConnection(connection);
                var server           = new Server(serverConnection);

                var jobs = server.JobServer.Jobs.Cast <Job>().Where(x => x.DateLastModified >= lastrun & x.DeleteLevel == CompletionAction.Never);

                foreach (var job in jobs)
                {
                    if (ret != "All jobs" | ret != "Many jobs")
                    {
                        try
                        {
                            ret += ret + "(J) " + job.Name;
                        }
                        catch (Exception ex)
                        {
                            _logger.LogWarning("Many jobs exported");
                            ret = "Many jobs";
                        }
                    }
                    var ddl = job.Script(
                        new ScriptingOptions()
                    {
                        DriAll             = true,
                        AgentAlertJob      = true,
                        AgentNotify        = true,
                        AllowSystemObjects = true
                    }
                        ).Cast <string>().ToArray();

                    File.WriteAllLines(Path.Combine(workPath, "J", job.JobID.ToString()), ddl);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("GetJobsToFile " + ex.Message);
            }
            _logger.LogInformation(@"Complete get jobs from " + serverName);

            return(ret);
        }
Esempio n. 40
0
        public string ConvertToIranTimeString(DateTime Date)
        {
            //string zoneId = "Iran Standard Time";
            //TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
            //DateTime result = TimeZoneInfo.ConvertTimeFromUtc(Date, tzi);

            Date = Date.AddMinutes(-150);

            PersianCalendar pc = new PersianCalendar();
            string year = pc.GetYear(Date).ToString();
            string Month = pc.GetMonth(Date).ToString();
            string Day = pc.GetDayOfMonth(Date).ToString();
            string Hour = pc.GetHour(Date).ToString();
            string Minute = pc.GetMinute(Date).ToString();

            if (Month.Length == 1)
            {
                Month = "0" + Month;
            }
            if (Day.Length == 1)
            {
                Day = "0" + Day;
            }
            if (Hour.Length == 1)
            {
                Hour = "0" + Hour;
            }
            if (Minute.Length == 1)
            {
                Minute = "0" + Minute;
            }

            return year + "/" + Month + "/" + Day + " " + Hour + ":" + Minute;
        }
Esempio n. 41
0
        private void button1_Click(object sender, EventArgs e)
        {
            dataGridView1.Visible = false;
            dataGridView2.Visible = false;

            DateTime time = new DateTime();
            time = time.AddHours(int.Parse(textBox1.Text));
            time = time.AddMinutes(int.Parse(textBox2.Text));
            t = time;

               Glades.list_ctrl_train.Clear();

            for (int i = 0; i < list_poezdov.Count; i++)
            {
                for (int j = 0; j < marshruts.Count; j++)
                {
                    if (list_poezdov[i].ID == marshruts[j].ID)
                    {
                        list_poezdov[i].last_ostanovka(marshruts[j], time);
                    }
                }
            }
            pictureBox1.Controls.Clear();
            glades.create_ctrl();
            load_event(Glades.list_ctrl_train);
        }
Esempio n. 42
0
        private static DateTimeResolutionResult GetDateTimeResult(string unitStr, string numStr, System.DateTime referenceTime, bool future)
        {
            System.DateTime time;
            var             ret          = new DateTimeResolutionResult();
            int             futureOrPast = future ? 1 : -1;

            switch (unitStr)
            {
            case "H":
                time = referenceTime.AddHours(double.Parse(numStr) * futureOrPast);
                break;

            case "M":
                time = referenceTime.AddMinutes(double.Parse(numStr) * futureOrPast);
                break;

            case "S":
                time = referenceTime.AddSeconds(double.Parse(numStr) * futureOrPast);
                break;

            default:
                return(ret);
            }

            ret.Timex       = $"{FormatUtil.LuisDateTime(time)}";
            ret.FutureValue = ret.PastValue = time;
            ret.Success     = true;
            return(ret);
        }
Esempio n. 43
0
 public static DateTime GetNextAvailability(DateTime currentAvailability, TimeSpan backoffInterval, int retryAttempts)
 {
     double backoffIntervalMinutes = backoffInterval.Minutes >= 1 ? backoffInterval.Minutes : 1;
     int backoffMinutes = (int)((1d / backoffIntervalMinutes) * (Math.Pow(backoffIntervalMinutes, Math.Min(retryAttempts, retryCeiling)) - 1d));
     backoffMinutes = backoffMinutes >= 1 ? backoffMinutes : 1;
     return currentAvailability.AddMinutes(backoffMinutes);
 }
Esempio n. 44
0
    public static bool CalculateWin()
    {
        //int premios_restantes = Premio.GetRestantes ();
        int premios_restantes = int.Parse(Main.GetConfig ("cantidad_premios"));

        if (premios_restantes > 0) {
            Hashtable last_premio = Premio.GetLastByEvento (Evento.GetActivoID ());

            DateTime last_date = new DateTime();
            if(last_premio["id"] != null){
                last_date = DateTime.Parse(last_premio["fecha_entregado"].ToString());
            }else{
                last_date = DateTime.Parse(GetConfig ("premios_start_date"));
            }

            DateTime end = DateTime.Parse(GetConfig ("premios_end_date"));
            TimeSpan duration = end - last_date;

            DateTime hora_proxima_entrega = last_date.AddMinutes(duration.TotalMinutes / premios_restantes);

            if(System.DateTime.Now > hora_proxima_entrega){
                return true;
            }
        }
        return false;
    }
Esempio n. 45
0
        private string GetViewsToFileV2(SqlConnection connection, System.DateTime lastrun, string serverName, string dbName)
        {
            _logger.LogInformation(@"Begin get V from " + serverName + " " + dbName);
            var ret      = "";
            var workPath = Path.Combine(workDir, serverName, dbName);

            try
            {
                if (Directory.Exists(Path.Combine(workPath, "V")))
                {
                    lastrun = lastrun.AddMinutes(-2);
                }
                else
                {
                    ret = "All Tables";
                    Directory.CreateDirectory(Path.Combine(workPath, "V"));
                    lastrun = new System.DateTime(1900, 1, 1);
                }


                var serverConnection = new ServerConnection(connection);
                var server           = new Server(serverConnection);

                var sps = server.Databases[dbName].Views.Cast <View>()
                          .Where(x => x.DateLastModified >= lastrun);

                foreach (var sp in sps)
                {
                    if (ret != "All View" | ret != "Many Views")
                    {
                        try
                        {
                            ret += ret + "(V) " + sp.Name;
                        }
                        catch (Exception ex)
                        {
                            _logger.LogWarning("Many Views exported");
                            ret = "Many Views";
                        }
                    }
                    var ddl = sp.Script(
                        new ScriptingOptions()
                    {
                        SchemaQualify = true,
                        DriAll        = true,
                        Permissions   = true
                    }
                        ).Cast <string>().ToArray();

                    File.WriteAllLines(Path.Combine(workPath, "V", sp.Name + "_" + sp.Schema), ddl);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("GetViewsToFile " + ex.Message);
            }
            _logger.LogInformation(@"Complete get V from " + serverName + " " + dbName);
            return(ret);
        }
Esempio n. 46
0
 public void TimerRunner()
 {
     //disables main button and runs timer
     gameObject.GetComponent <Button>().interactable = false;
     obj.active   = true;
     RemaningTime = currentTime;
     RemaningTime = RemaningTime.AddMinutes(WaitMinutes);
 }
Esempio n. 47
0
        public string GetLinkedServersToFilesV2(SqlConnection connection, System.DateTime lastrun, string serverName)
        {
            _logger.LogInformation(@"Begin get linked servers from " + serverName);
            var ret      = "";
            var workPath = Path.Combine(workDir, serverName);

            try
            {
                if (Directory.Exists(Path.Combine(workPath, "LS")))
                {
                    lastrun = lastrun.AddMinutes(-2);
                }
                else
                {
                    ret = "All linked servers";
                    Directory.CreateDirectory(Path.Combine(workPath, "LS"));
                    lastrun = new System.DateTime(1900, 1, 1);
                }


                var serverConnection = new ServerConnection(connection);
                var server           = new Server(serverConnection);

                var linkedServers = server.LinkedServers.Cast <LinkedServer>().Where(x => x.DateLastModified >= lastrun);

                foreach (var ls in linkedServers)
                {
                    if (ret != "All linked servers" | ret != "Many LS")
                    {
                        try
                        {
                            ret += ret + "(LS) " + ls.Name;
                        }
                        catch (Exception ex)
                        {
                            _logger.LogWarning("Many jobs exported");
                            ret = "Many LS";
                        }
                    }
                    var ddl = ls.Script(
                        new ScriptingOptions()
                    {
                        DriAll             = true,
                        AllowSystemObjects = true
                    }
                        ).Cast <string>().ToArray();

                    File.WriteAllLines(Path.Combine(workPath, "LS", ls.ID.ToString()), ddl);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("GetLinkedServersToFile " + ex.Message);
            }
            _logger.LogInformation(@"Complete get linked servers from " + serverName);

            return(ret);
        }
Esempio n. 48
0
 public System.DateTime GetDateTime(bool correctTZ)
 {
     System.DateTime result = myValue;
     if (correctTZ && timezone != NoTimezone)
     {
         result.AddMinutes(-timezone);
     }
     return(result);
 }
Esempio n. 49
0
        public static System.DateTime Round(this System.DateTime dateTime, RoundTo rt)
        {
            System.DateTime rounded;

            switch (rt)
            {
            case RoundTo.Second:
            {
                rounded = new System.DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Kind);
                if (dateTime.Millisecond >= 500)
                {
                    rounded = rounded.AddSeconds(1);
                }
                break;
            }

            case RoundTo.Minute:
            {
                rounded = new System.DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, 0, dateTime.Kind);
                if (dateTime.Second >= 30)
                {
                    rounded = rounded.AddMinutes(1);
                }
                break;
            }

            case RoundTo.Hour:
            {
                rounded = new System.DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, 0, 0, dateTime.Kind);
                if (dateTime.Minute >= 30)
                {
                    rounded = rounded.AddHours(1);
                }
                break;
            }

            case RoundTo.Day:
            {
                rounded = new System.DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0, dateTime.Kind);
                if (dateTime.Hour >= 12)
                {
                    rounded = rounded.AddDays(1);
                }
                break;
            }

            default:
            {
                throw new ArgumentOutOfRangeException("rt");
            }
            }

            return(rounded);
        }
    // Set timer and PersisistentManager vars for timeout tracking
    public void SetTimer()
    {
        // Check current time and add constraint given timeout onto it
        System.DateTime now     = System.DateTime.Now;
        double          timeout = System.Convert.ToDouble(PersistentManager.Instance.timeOut);

        System.DateTime tmp = now.AddMinutes(timeout);

        // Update var for later checking
        PersistentManager.Instance.endTime = tmp;
    }
Esempio n. 51
0
 public static Altova.Types.DateTime DatetimeFromDateAndTime(Altova.Types.DateTime date, Altova.Types.DateTime time)
 {
     Altova.Types.DateTime ret   = new Altova.Types.DateTime(date);
     System.DateTime       sysdt = ret.Value;
     sysdt     = sysdt.AddHours(-date.Value.Hour + time.Value.Hour);
     sysdt     = sysdt.AddMinutes(-date.Value.Minute + time.Value.Minute);
     sysdt     = sysdt.AddSeconds(-date.Value.Second + time.Value.Second);
     sysdt     = sysdt.AddMilliseconds(-date.Value.Millisecond + time.Value.Millisecond);
     ret.Value = sysdt;
     return(ret);
 }
Esempio n. 52
0
 private void Update()
 {
     timePassed += Time.deltaTime;
     if (timePassed >= 1)
     {
         timePassed -= 1;
         moment      = moment.AddMinutes(1);
         CheckCallBacks();
         SetClockOnScreen();
     }
 }
Esempio n. 53
0
    // Use this for initialization
    void Start()
    {
        JSONUtils.initJsonObjectConversion();

        System.DateTime date = System.DateTime.Now;

        for (int i = 0; i < 5; ++i)
        {
            date = date.AddMinutes(-6);
            StartCoroutine(getMatchIDList(DateMath.RoundDateToFive(date)));
        }
    }
Esempio n. 54
0
        /// <summary>
        /// Adds a tooltip to a Steam mod showing its update status.
        /// </summary>
        /// <param name="tooltip">The tooltip under construction.</param>
        /// <param name="modUpdate">The mod update executor which can update this mod.</param>
        /// <param name="localDate">The local last update date.</param>
        /// <param name="updButton">The button to be used for updating this mod.</param>
        /// <returns>The status of the Steam mod.</returns>
        private static ModStatus AddSteamUpdate(StringBuilder tooltip, ModToUpdate modUpdate,
                                                System.DateTime localDate, PButton updButton)
        {
            var steamDate = modUpdate.LastSteamUpdate;
            var updated   = ModStatus.Disabled;

            if (steamDate > System.DateTime.MinValue)
            {
                // Generate tooltip for mod's current date and last Steam update
                var ours       = ModUpdateInfo.FindModInConfig(modUpdate.SteamID.m_PublishedFileId);
                var ourDate    = System.DateTime.MinValue;
                var globalDate = modUpdate.LastSteamUpdate;
                // Do we have a better estimate?
                if (ours != null)
                {
                    ourDate = new System.DateTime(ours.LastUpdated, DateTimeKind.Utc);
                }
                // Allow some time for download delays etc
                if (localDate.AddMinutes(UPDATE_JITTER) >= globalDate)
                {
                    tooltip.Append(ModUpdateDateStrings.MOD_UPDATED);
                    updated = ModStatus.UpToDate;
                }
                else if (ourDate.AddMinutes(UPDATE_JITTER) >= globalDate)
                {
                    tooltip.Append(ModUpdateDateStrings.MOD_UPDATED_BYUS);
                    localDate = ourDate;
                    updated   = ModStatus.UpToDateLocal;
                }
                else
                {
                    tooltip.Append(ModUpdateDateStrings.MOD_OUTDATED);
                    updated = ModStatus.Outdated;
                }
                // AppendLine appends platform specific separator
                tooltip.Append("\n");
                tooltip.AppendFormat(ModUpdateDateStrings.LOCAL_UPDATE, localDate.
                                     ToLocalTime());
                tooltip.Append("\n");
                tooltip.AppendFormat(ModUpdateDateStrings.STEAM_UPDATE, globalDate.
                                     ToLocalTime());
                updButton.OnClick = new ModUpdateTask(modUpdate).TryUpdateMods;
            }
            else
            {
                // Steam update could not be determined
                tooltip.AppendFormat(ModUpdateDateStrings.LOCAL_UPDATE, localDate.
                                     ToLocalTime());
                tooltip.Append("\n");
                tooltip.AppendFormat(ModUpdateDateStrings.STEAM_UPDATE_UNKNOWN);
            }
            return(updated);
        }
        public static DateObject SafeCreateFromValue(this DateObject datetime, int year, int month, int day, int hour, int minute, int second)
        {
            if (IsValidDate(year, month, day) && IsValidTime(hour, minute, second))
            {
                datetime = datetime.SafeCreateFromValue(year, month, day);
                datetime = datetime.AddHours(hour - datetime.Hour);
                datetime = datetime.AddMinutes(minute - datetime.Minute);
                datetime = datetime.AddSeconds(second - datetime.Second);
            }

            return(datetime);
        }
Esempio n. 56
0
        private void EventoWatchdog(object source, System.Timers.ElapsedEventArgs e)
        {
            //Hace un minuto que no se dispara un evento. Reinicio el servidor fiscal.
            if (System.DateTime.Now > Watchdog_LastOp.AddMinutes(5))
            {
                System.IO.BinaryWriter wr = new System.IO.BinaryWriter(new System.IO.FileStream(Lfx.Environment.Folders.ApplicationDataFolder + "watchdog.log", System.IO.FileMode.Append));
                wr.Write("ServidorFiscal: REBOOT " + System.DateTime.Now.ToString() + System.Environment.NewLine);
                wr.Close();

                Impresora.EstadoServidor = Lazaro.Impresion.Comprobantes.Fiscal.EstadoServidorFiscal.Reiniciando;
            }
        }
Esempio n. 57
0
    /**
     * 에너지 추가되는 시간 체크하는 함수
     */
    void EnergyTimeCheck()
    {
        DATA   data          = DATA.getData();  // PlayerPrefs 데이터를 관리하는 함수를 가져옴
        string nowTimeString = data.ENERGYTIME; // 에너지가 사용되는 마지막 시간을 가져옴

        // 에너지사용마지막 시간이 비어있거나, 에너지가 가득 자있을 경우 반환한다.
        if (nowTimeString.Equals("") || energy >= 7)
        {
            return;
        }


        System.DateTime saveTime = System.Convert.ToDateTime(nowTimeString); // 마지막 시간의 문자열을 시간형태로 변환
        System.DateTime nowTime  = System.DateTime.Now;                      // 현재시간을 가져옴

        System.TimeSpan timeCal = nowTime - saveTime;                        // 두 시간 차를 구함

        int timeCalDay  = timeCal.Days;                                      // 날짜 차이
        int timeCalHour = timeCal.Hours;                                     // 시간 차이
        int timeCalMin  = timeCal.Minutes;                                   // 분 차이

        // 하루 이상 또는 1시간 이상 일 경우 풀에너지
        if (timeCalDay > 0 || timeCalHour > 0)
        {
            data.ENERGY     = DATA.MAXENERGY;
            data.ENERGYTIME = "";
        }
        else  // 분단위 일 경우 확인작업
        {
            int addEnergy = timeCalMin / 3; // 지나간 시간의 에너지 개수

            if ((energy + addEnergy) >= 7)  // 에너지 개수가 맥스일 경우
            {
                energy          = DATA.MAXENERGY;
                data.ENERGY     = DATA.MAXENERGY;
                data.ENERGYTIME = "";
            }
            else                            // 아닐 경우 시간 확인 및 타이머
            {
                // 에너지 추가 및 데이터 저장
                energy     += addEnergy;
                data.ENERGY = energy;

                // 추가된 에너지만큼의 시간 추가 및 마지막 시간 저장
                saveTime        = saveTime.AddMinutes(addEnergy * 3);
                data.ENERGYTIME = TextUtills.DateTimeToString(saveTime);

                // 이후 남은 시간 카운팅코르틴 시작
                StartCoroutine(EnergyChargeText());
            }
        }
    }
Esempio n. 58
0
    void updateClock()
    {
        if (fastforward == 0)
        {
            return;
        }

        timeofday = timeofday.AddMinutes(fastforward * 30);

        date.text = timeofday.ToString("yyyy-MM-dd");
        time.text = timeofday.ToString("HH:mm:ss");

        checkMissions();
    }
Esempio n. 59
0
        public static string GenerateRelativeUnitDateTimePeriodTimex(ref DateObject beginDateTime, ref DateObject endDateTime, DateObject referenceTime, string unitStr, int swift)
        {
            string prefix        = Constants.GeneralPeriodPrefix + Constants.TimeTimexPrefix;
            string durationTimex = string.Empty;

            switch (unitStr)
            {
            case Constants.TimexDay:
                endDateTime   = DateObject.MinValue.SafeCreateFromValue(beginDateTime.Year, beginDateTime.Month, beginDateTime.Day);
                endDateTime   = endDateTime.AddDays(1).AddSeconds(-1);
                durationTimex = prefix + (endDateTime - beginDateTime).TotalSeconds + Constants.TimexSecond;
                break;

            case Constants.TimexHour:
                beginDateTime = swift > 0 ? beginDateTime : referenceTime.AddHours(swift);
                endDateTime   = swift > 0 ? referenceTime.AddHours(swift) : endDateTime;
                durationTimex = prefix + "1" + Constants.TimexHour;
                break;

            case Constants.TimexMinute:
                beginDateTime = swift > 0 ? beginDateTime : referenceTime.AddMinutes(swift);
                endDateTime   = swift > 0 ? referenceTime.AddMinutes(swift) : endDateTime;
                durationTimex = prefix + "1" + Constants.TimexMinute;
                break;

            case Constants.TimexSecond:
                beginDateTime = swift > 0 ? beginDateTime : referenceTime.AddSeconds(swift);
                endDateTime   = swift > 0 ? referenceTime.AddSeconds(swift) : endDateTime;
                durationTimex = prefix + "1" + Constants.TimexSecond;
                break;

            default:
                return(string.Empty);
            }

            return(GenerateDateTimePeriodTimex(beginDateTime, endDateTime, durationTimex));
        }
Esempio n. 60
0
            public void Set(System.Globalization.Calendar calendar, int field, int fieldValue)
            {
                if (this[calendar] != null)
                {
                    System.DateTime tempDate = ((CalendarProperties)this[calendar]).dateTime;
                    switch (field)
                    {
                    case CalendarManager.DATE:
                        tempDate = tempDate.AddDays(fieldValue - tempDate.Year);
                        break;

                    case CalendarManager.HOUR:
                        tempDate = tempDate.AddHours(fieldValue - tempDate.Hour);
                        break;

                    case CalendarManager.MILLISECOND:
                        tempDate = tempDate.AddMilliseconds(fieldValue - tempDate.Millisecond);
                        break;

                    case CalendarManager.MINUTE:
                        tempDate = tempDate.AddMinutes(fieldValue - tempDate.Minute);
                        break;

                    case CalendarManager.MONTH:
                        //In java.util.Calendar, Month value is 0-based. e.g., 0 for January
                        tempDate = tempDate.AddMonths(fieldValue - (tempDate.Month + 1));
                        break;

                    case CalendarManager.SECOND:
                        tempDate = tempDate.AddSeconds(fieldValue - tempDate.Second);
                        break;

                    case CalendarManager.YEAR:
                        tempDate = tempDate.AddYears(fieldValue - tempDate.Year);
                        break;

                    default:
                        break;
                    }
                    ((CalendarProperties)this[calendar]).dateTime = tempDate;
                }
                else
                {
                    CalendarProperties tempProps = new CalendarProperties();
                    tempProps.dateTime = System.DateTime.Now;
                    this.Add(calendar, tempProps);
                    this.Set(calendar, field, fieldValue);
                }
            }