Esempio n. 1
0
    public static bool TryGetFromNaturalFormat(string text, out TimeSpan result) {
      result = TimeSpan.Zero;

      var matches = Regex.Matches(text, @"(\d+)[ \t]*([a-zA-Z]+)");
      if (matches.Count == 0) return false;

      foreach (Match match in matches) {
        var number = match.Groups[1].Value;
        var unit = match.Groups[2].Value;

        double value;
        if (!double.TryParse(number, out value))
          return false;

        switch (unit) {
          case "d":
          case "day":
          case "days": result = result.Add(TimeSpan.FromDays(value)); break;
          case "h":
          case "hour":
          case "hours": result = result.Add(TimeSpan.FromHours(value)); break;
          case "m":
          case "min":
          case "minute":
          case "minutes": result = result.Add(TimeSpan.FromMinutes(value)); break;
          case "s":
          case "sec":
          case "second":
          case "seconds": result = result.Add(TimeSpan.FromSeconds(value)); break;
          default: return false;
        }
      }
      return true;
    }
Esempio n. 2
0
        /// <summary>
        /// Converts the string to TimeSpan
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static TimeSpan ConvertStringToTimeSpan(string s)
        {
            var timeSpanRegex = new Regex(
                string.Format(@"\s*(?<{0}>\d+)\s*(?<{1}>({2}|{3}|{4}|{5}|\Z))",
                              Quantity, Unit, Days, Hours, Minutes, Seconds),
                              RegexOptions.IgnoreCase);
            var matches = timeSpanRegex.Matches(s);

            var ts = new TimeSpan();
            foreach (Match match in matches)
            {
                if (Regex.IsMatch(match.Groups[Unit].Value, @"\A" + Days))
                {
                    ts = ts.Add(TimeSpan.FromDays(double.Parse(match.Groups[Quantity].Value)));
                }
                else if (Regex.IsMatch(match.Groups[Unit].Value, Hours))
                {
                    ts = ts.Add(TimeSpan.FromHours(double.Parse(match.Groups[Quantity].Value)));
                }
                else if (Regex.IsMatch(match.Groups[Unit].Value, Minutes))
                {
                    ts = ts.Add(TimeSpan.FromMinutes(double.Parse(match.Groups[Quantity].Value)));
                }
                else if (Regex.IsMatch(match.Groups[Unit].Value, Seconds))
                {
                    ts = ts.Add(TimeSpan.FromSeconds(double.Parse(match.Groups[Quantity].Value)));
                }
                else
                {
                    // Quantity given but no unit, default to Hours
                    ts = ts.Add(TimeSpan.FromHours(double.Parse(match.Groups[Quantity].Value)));
                }
            }
            return ts;
        }
        public TimeSpan ParseTime(string timeString)
        {
            if (string.IsNullOrWhiteSpace(timeString) || timeString == "0000")
                return new TimeSpan(0);

            timeString = timeString.Trim();

            var result = new TimeSpan();
            int minutes;

            if (timeString[timeString.Length - 1] == 'H')
            {
                result = TimeSpan.FromSeconds(30);
                timeString = timeString.Remove(timeString.Length - 1);
            }

            if (timeString == string.Empty)
                return result;

            if (timeString.Length <= 2)
            {
                try
                {
                    minutes = int.Parse(timeString);
                }
                catch (FormatException)
                {
                    return new TimeSpan(0);
                }

                return result.Add(TimeSpan.FromMinutes(minutes));
            }

            if (timeString.Length == 4)
            {
                try
                {
                    var hours = int.Parse(timeString.Substring(0, 2));
                    result = result.Add(TimeSpan.FromHours(hours));

                    minutes = int.Parse(timeString.Substring(2, 2));
                    result = result.Add(TimeSpan.FromMinutes(minutes));
                }
                catch (FormatException)
                {
                    return new TimeSpan(0);
                }
            }

            return result;
        }
Esempio n. 4
0
        /// <summary>
        /// Parses the specified value.
        /// </summary>
        /// <param name="value">
        /// The value.
        /// </param>
        /// <param name="formatString">
        /// The format string.
        /// </param>
        /// <returns>
        /// A TimeSpan.
        /// </returns>
        public static TimeSpan Parse(string value, string formatString = null)
        {
            // todo: parse the formatstring and evaluate the timespan
            // Examples
            // FormatString = MM:ss, value = "91:12" => 91 minutes 12seconds
            // FormatString = HH:mm, value = "91:12" => 91 hours 12minutes
            if (value.Contains(":"))
            {
                return TimeSpan.Parse(value, CultureInfo.InvariantCulture);
            }

            // otherwise support values as:
            // "12d"
            // "12d 5h"
            // "5m 3s"
            // "12.5d"
            var total = new TimeSpan();
            foreach (Match m in ParserExpression.Matches(value))
            {
                string number = m.Groups[1].Value;
                if (string.IsNullOrWhiteSpace(number))
                {
                    continue;
                }

                double d = double.Parse(number.Replace(',', '.'), CultureInfo.InvariantCulture);
                string unit = m.Groups[2].Value;
                switch (unit.ToLower())
                {
                    case "":
                    case "d":
                        total = total.Add(TimeSpan.FromDays(d));
                        break;
                    case "h":
                        total = total.Add(TimeSpan.FromHours(d));
                        break;
                    case "m":
                    case "'":
                        total = total.Add(TimeSpan.FromMinutes(d));
                        break;
                    case "\"":
                    case "s":
                        total = total.Add(TimeSpan.FromSeconds(d));
                        break;
                }
            }

            return total;
        }
        private static void PrintDayStats(IReadOnlyList<DateTime> dates)
        {
            var totalMinutesIn = new TimeSpan(0, 0, 0, 0);
            var totalMinutesOut = new TimeSpan(0, 0, 0, 0);

            DateTime lastDate = dates[0];

            var isIn = false;
            for (int i = 1; i < dates.Count; i++)
            {
                var instance = dates[i];
                isIn = !isIn;
                if (isIn)
                {
                    totalMinutesIn = totalMinutesIn.Add(instance.Subtract(lastDate));
                }
                else
                {
                    totalMinutesOut = totalMinutesOut.Add(instance.Subtract(lastDate));
                }
                lastDate = instance;
            }
            Console.WriteLine("Total minutes in: {0}, out: {1}, extra: {2}", totalMinutesIn, totalMinutesOut, totalMinutesIn.Subtract(Day));
            _overtime = _overtime.Add(totalMinutesIn.Subtract(Day));
        }
Esempio n. 6
0
        public InListOutOfList(List<SubCalendarEvent> FullList, List<List<List<SubCalendarEvent>>> AllMyList, List<TimeLine> MyFreeSpots)
        {
            DictData_TimeLine = new Dictionary<List<TimeLine>, List<SubCalendarEvent>>();
            foreach (List<List<SubCalendarEvent>> ListToCheck in AllMyList)
            {
                List<SubCalendarEvent> TotalList = new List<SubCalendarEvent>();
                int i = 0;
                List<TimeLine> timeLineEntry = new List<TimeLine>();
                foreach (List<SubCalendarEvent> myList in ListToCheck)
                {
                    TimeLine myTimeLine = new TimeLine(MyFreeSpots[i].Start, MyFreeSpots[i].End);
                    TotalList.AddRange(myList);

                    TimeSpan TotalTimeSpan = new TimeSpan(0);
                    foreach (SubCalendarEvent mySubEvent in myList)
                    {
                        TotalTimeSpan=TotalTimeSpan.Add(mySubEvent.ActiveSlot.BusyTimeSpan);
                    }

                    BusyTimeLine EffectivebusySlot = new BusyTimeLine("1000000_1000001", MyFreeSpots[i].Start, MyFreeSpots[i].Start.Add(TotalTimeSpan));
                    myTimeLine.AddBusySlots(EffectivebusySlot);
                    timeLineEntry.Add(myTimeLine);
                    i++;
                }

                DictData_TimeLine.Add(timeLineEntry, Utility.NotInList_NoEffect(FullList, TotalList));
            }
        }
Esempio n. 7
0
    public void SetTimer(TimeSpan time)
    {
        TimeSpan = time.Add(new TimeSpan(0, 0, 1));

        string t = "";
        switch (TimerType)
        {
            case TimerType.SecondsTimer:
                t = time.TotalSeconds.ToString("00");
                break;
            case TimerType.MinutesTimer:
                t = (time.Days * 24 * 60 + time.Hours * 60 + time.Minutes).ToString("00") + ":" +
                       time.Seconds.ToString("00");
                break;
            case TimerType.HoursTimer:
                t = (time.Days * 24 + time.Hours).ToString("00") + ":" + time.Minutes.ToString("00") + ":" +
                       time.Seconds.ToString("00");
                break;
        }

        if (GUITimer != null)
        {
            GUITimer.text = t;
        }

        if (Timer != null)
        {
            Timer.text = t;
        }

    }
        public void Connect()
        {
            if (_client != null) return;
            
            try
            {
                ReadyState = ReadyStates.CONNECTING;

                _client = new TcpClient();
                _connecting = true;
                _client.BeginConnect(_host, _port, OnRunClient, null);

                var waiting = new TimeSpan();
                while (_connecting && waiting < ConnectTimeout)
                {
                    var timeSpan = new TimeSpan(0, 0, 0, 0, 100);
                    waiting = waiting.Add(timeSpan);
                    Thread.Sleep(timeSpan.Milliseconds);
                }
                if (_connecting) throw new Exception("Timeout");
            }
            catch (Exception)
            {
                Disconnect();
                OnFailedConnection(null);
            }
        }
        public TimeSpan GetGreenTimeAboveSpeed(DateTime StartTime, DateTime EndTime, int SetpointSpeed)
        {
            
            TimeSpan ret_value = new TimeSpan(0, 0, 0);
            TimeSpan ShiftDuration = new TimeSpan(12, 0, 0);
            TimeSpan add_value = new TimeSpan(0, 0, this.Discontinuity);
            for (int i = 0; i < GraphicLineDataArr.Length-1; i++)
            {
                try
                {
                    if (GraphicLineDataArr[i] != null && GraphicLineDataArr[i].datetime > StartTime && GraphicLineDataArr[i].datetime <= EndTime && GraphicLineDataArr[i].value >= SetpointSpeed)
                    {
                        //if ((GraphicLineDataArr[i].datetime-StartTime).TotalSeconds<=1)
                        //    ret_value = ret_value.Add(GraphicLineDataArr[i].datetime - StartTime);

                        //if ((GraphicLineDataArr[i].datetime - StartTime).TotalSeconds > 1)
                            ret_value = ret_value.Add(add_value);

                        //if ((EndTime - GraphicLineDataArr[i].datetime).TotalSeconds <= 1)
                        //    ret_value = ret_value.Add(EndTime - GraphicLineDataArr[i].datetime);
                    }
                }
                catch
                {
                    MessageBox.Show("catch GetGreenTimeAboveSpeed"+i.ToString());
                }
            }
            //ret_value = ShiftDuration - ret_value;
            return ret_value;
            //return EndTime - StartTime;
        }
Esempio n. 10
0
        public void Delay()
        {
            //delay to test (3 seconds)
            var delay = new TimeSpan(0, 0, 0, 3 /* seconds */);
            //tollerance (actual time should be between 2.9 and 3.1 seconds)
            var tollerance = new TimeSpan(0, 0, 0, 0, 100 /* milliseconds */);

            Stopwatch stopwatch = new Stopwatch();
            Timer timer = new Timer();

            Loop.Current.QueueWork(() => {
                stopwatch.Start();
                timer.Start(delay, TimeSpan.Zero, () =>
                {
                    stopwatch.Stop();
                    timer.Stop();
                    timer.Close();
                });
            });

            Loop.Current.Run();

            Assert.GreaterOrEqual(stopwatch.Elapsed, delay.Subtract(tollerance));
            Assert.Less(stopwatch.Elapsed, delay.Add(tollerance));
        }
Esempio n. 11
0
        static void Main(string[] args)
        {
            //Creating Timespan
            var timeSpan  = new System.TimeSpan(1, 2, 3);
            var timeSpan1 = new System.TimeSpan(1, 0, 0);
            var timeSpan2 = System.TimeSpan.FromHours(1);

            var start    = DateTime.Now;
            var end      = DateTime.Now.AddMinutes(2);
            var duration = end - start;

            Console.WriteLine("Duration: " + duration);

            //Properties
            Console.WriteLine("Minutes: " + timeSpan.Minutes);
            Console.WriteLine("Total Minutes: " + timeSpan.TotalMinutes);

            //Add
            Console.WriteLine("Add Example: " + timeSpan.Add(System.TimeSpan.FromMinutes(8)));
            Console.WriteLine("Subtract Example: " + timeSpan.Subtract(System.TimeSpan.FromMinutes(2)));

            // ToString
            Console.WriteLine("ToString " + timeSpan.ToString());

            // Parse
            Console.WriteLine("Parse: " + System.TimeSpan.Parse("01:02:03"));
        }
        public void RemindStartOfWeek(Reminder startOfWeekReminder)
        {
            var dateToday = DateTime.Now;
            TimeSpan accumulatedTime = new TimeSpan(0, 0, 0);
            if (dateToday.ToString("ddd") == "Mon" && dateToday.Hour == startOfWeekReminder.TimeOfActivation.Hour && dateToday.Minute == startOfWeekReminder.TimeOfActivation.Minute ) //should get the hour from a reminder!dateToday.ToString("h tt") == "4 PM"
            {
                IRepository repo = new Repository();
                var startOfWeekTime = dateToday.AddDays(-7);
                //var dateTomorrow = dateToday.AddDays(1);

                var list = repo.GetByStartDate(startOfWeekTime, dateToday);

                foreach (SparkTask task in list)
                {
                    if(task.State != TaskState.reported){ accumulatedTime = accumulatedTime.Add(task.TimeElapsed); }
                }

                if (accumulatedTime >= new TimeSpan(36, 0, 0))
                {
                    ReminderEventArgs args = new ReminderEventArgs(startOfWeekReminder, new SparkTask()); //should be the reminder im using send the task can stay like this.
                    reminderControl.OnEventHaveToReport(args);
                    startOfWeekReminder.TimeOfActivation = startOfWeekReminder.TimeOfActivation.AddHours(1);
                    repo.Update(startOfWeekReminder);
                }

            }
        }
Esempio n. 13
0
        protected void DetailsView1_ItemCreated(object sender, EventArgs e)
        {
            TimeSpan startTime = new TimeSpan(7,0,0);
                                    TimeSpan increment = new TimeSpan(1,0,0);
             								TimeSpan[] timeList = new TimeSpan[14];

                                    //populate array with times incremented by an hour
                                    for (int i = 0; i <= 13; i++)
                                    {
                                                timeList[i] = startTime;
                                                startTime = startTime.Add(increment);
                                    }

                                    DropDownList ddl = DetailsView1.FindControl("ddlStart") as DropDownList;
                                    if (ddl != null)
                                    {
                                                ddl.DataSource = timeList;
                                    }

                                    DropDownList ddl2 = DetailsView1.FindControl("ddlEnd") as DropDownList;
                                    if (ddl2 != null)
                                    {
                                                ddl2.DataSource = timeList;
                                    }
        }
Esempio n. 14
0
        public List<ICongestionChargeInvoice> BuildInvoice(List<IChargeSummary> dailyCharges)
        {
            var invoices = new List<ICongestionChargeInvoice>();
            var groupedByDescription = dailyCharges.GroupBy(dc => dc.RateDescription);

            var total = 0m;
            foreach (var chargeRate in groupedByDescription)
            {
                var time = new TimeSpan();
                decimal cost = 0m;

                foreach (var day in chargeRate)
                {
                    time = time.Add(day.TimeSpent);
                    cost += day.Cost;
                }

                var totalRate = cost.TruncateDecimal(1);
                total += totalRate;

                invoices.Add(new CongestionChargeInvoice
                    {
                        Value = string.Format("{0}{1}", CurrencyAppend, totalRate.ToString("0.00")),
                        Description = string.Format("Charge for {0}h {1}m ({2}):", time.Hours, time.Minutes, chargeRate.Key)
                    });
            }

            invoices.Add(CalculateTotal(total));
            return invoices;
        }
        public void RemindEndOfWeek(Reminder endOfWeekReminder)
        {
            var dateToday = DateTime.Now;
            TimeSpan accumulatedTime = new TimeSpan(0,0,0);

            if (dateToday.ToString("ddd") == "Mon" && dateToday.Hour == endOfWeekReminder.TimeOfActivation.Hour && dateToday.Minute == endOfWeekReminder.TimeOfActivation.Minute)
            {
                IRepository repo = new Repository();
                var startOfWeekTime = dateToday.AddDays(-4);

                var list = repo.GetByStartDate(startOfWeekTime, dateToday);

                foreach(SparkTask task in list)
                {
                    if (task.State != TaskState.reported){ accumulatedTime = accumulatedTime.Add(task.TimeElapsed); }
                }

                if (accumulatedTime >= new TimeSpan(36, 0, 0))
                {
                    ReminderEventArgs args = new ReminderEventArgs(endOfWeekReminder, new SparkTask());
                    reminderControl.OnEventHaveToReport(args);
                    endOfWeekReminder.TimeOfActivation = endOfWeekReminder.TimeOfActivation.AddHours(1);
                    repo.Update(endOfWeekReminder);
                    //event!
                }
            }
        }
Esempio n. 16
0
    /// <summary>
    /// Main Thread Update
    /// </summary>
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.P))
        {
            util.ValueDebugger.showDebugger = !util.ValueDebugger.showDebugger;
        }

        util.Debugger.Log("", "", SkipLogging: true);

        if (!gamePaused)
        {
            l = MainThreadScripts.Count;
            for (i = 0; i < l; i++)
            {
                if (MainThreadScripts[i].enabled)
                {
                    MainThreadScripts[i].MainUpdate();
                }
            }
        }
        else
        {
            PausedTime.Add(new System.TimeSpan(0, 0, 0, 0, Mathf.FloorToInt(Time.deltaTime * 1000)));
        }
        //if (secondaryThread.ThreadState != ThreadState.Running )
        //    secondaryThread.Start();
    }
Esempio n. 17
0
        public static bool TryParse(string text, out TimeSpan value)
        {
            value = TimeSpan.Zero;

              var daysMatch = TimeSpanDaysRegex.Match(text);
              var hoursMatch = TimeSpanHoursRegex.Match(text);
              var minutesMatch = TimeSpanMinutesRegex.Match(text);
              var secondsMatch = TimeSpanSecondsRegex.Match(text);

              if (daysMatch.Success)
              {
            double days;
            if (double.TryParse(daysMatch.Groups["days"].Value, out days))
              value = value.Add(TimeSpan.FromDays(days));
            else
              return false;
              }

              if (hoursMatch.Success)
              {
            double hours;
            if (double.TryParse(hoursMatch.Groups["hours"].Value, out hours))
              value = value.Add(TimeSpan.FromHours(hours));
            else
              return false;
              }

              if (minutesMatch.Success)
              {
            double minutes;
            if (double.TryParse(minutesMatch.Groups["minutes"].Value, out minutes))
              value = value.Add(TimeSpan.FromMinutes(minutes));
            else
              return false;
              }

              if (secondsMatch.Success)
              {
            double seconds;
            if (double.TryParse(secondsMatch.Groups["seconds"].Value, out seconds))
              value = value.Add(TimeSpan.FromSeconds(seconds));
            else
              return false;
              }

              return daysMatch.Success || hoursMatch.Success || minutesMatch.Success || secondsMatch.Success;
        }
 private  PhasedBackoffWaitStrategy(TimeSpan spinTimeoutMillis,
                              TimeSpan yieldTimeoutMillis,
                              IBlockingStrategy lockingStrategy)
 {
     this.spinTimeoutNanos = spinTimeoutMillis;
     this.yieldTimeoutNanos = spinTimeoutNanos.Add(yieldTimeoutMillis);
     this.lockingStrategy = lockingStrategy;
 }
Esempio n. 19
0
 public ProcessaRes()
 {
     //Inizializzo il vettore dei risultati
     for (TimeSpan i = new TimeSpan(0, 0, 0); i < new TimeSpan(23, 59, 59); i = i.Add(new TimeSpan(0, 5, 0)))
     {
         giornata[i] = new Res();
     }
 }
Esempio n. 20
0
        private void AnimateLayout()
        {
            var startDelay = new TimeSpan();

            foreach (UIElement child in Children)
            {
                Point arrangePosition;
                Transform currentTransform = GetCurrentLayoutInfo(child, out arrangePosition);

                bool bypassTransform = _isAnimationValid != (int) GetValue(IsAnimationValidProperty);

                // If we had previously stored an arrange position, see if it has moved
                if (child.ReadLocalValue(SavedArrangePositionProperty) != DependencyProperty.UnsetValue)
                {
                    var savedArrangePosition = (Point) child.GetValue(SavedArrangePositionProperty);

                    // If the arrange position hasn't changed, then we've already set up animations, etc
                    // and don't need to do anything
                    if (!AreClose(savedArrangePosition, arrangePosition))
                    {
                        // If we apply the current transform to the saved arrange position, we'll see where
                        // it was last rendered
                        Point lastRenderPosition = currentTransform.Transform(savedArrangePosition);
                        if (bypassTransform)
                            lastRenderPosition = (Point) child.GetValue(SavedCurrentPositionProperty);
                        else
                            child.SetValue(SavedCurrentPositionProperty, lastRenderPosition);

                        // Transform the child from the new location back to the old position
                        var newTransform = new TranslateTransform();
                        SetLayout2LayoutTransform(child, newTransform);

                        // Decay the transformation with an animation
                        double startValue = lastRenderPosition.X - arrangePosition.X;
                        newTransform.BeginAnimation(TranslateTransform.XProperty,
                                                    MakeStaticAnimation(startValue, startDelay));
                        newTransform.BeginAnimation(TranslateTransform.XProperty, MakeAnimation(startValue, startDelay),
                                                    HandoffBehavior.Compose);
                        startValue = lastRenderPosition.Y - arrangePosition.Y;
                        newTransform.BeginAnimation(TranslateTransform.YProperty,
                                                    MakeStaticAnimation(startValue, startDelay));
                        newTransform.BeginAnimation(TranslateTransform.YProperty, MakeAnimation(startValue, startDelay),
                                                    HandoffBehavior.Compose);

                        // Next element starts to move a little later
                        startDelay = startDelay.Add(CascadingDelay);
                    }
                }

                // Save off the previous arrange position				
                child.SetValue(SavedArrangePositionProperty, arrangePosition);
            }
            // currently WPF doesn't allow me to read a value right after the call to BeginAnimation
            // this code enables me to trick it and know whether I can trust the current position or not.
            _isAnimationValid = (int) GetValue(IsAnimationValidProperty) + 1;
            BeginAnimation(IsAnimationValidProperty,
                           new Int32Animation(_isAnimationValid, _isAnimationValid, new Duration(), FillBehavior.HoldEnd));
        }
Esempio n. 21
0
 private static TimeSpan GetRecurrence(Event evt)
 {
     TimeSpan RecurrencyInterval = new TimeSpan();
     if (evt.RRule != null)
     {
         foreach (Recur r in evt.RRule)
         {
             switch (r.Frequency)
             {
                 case Recur.FrequencyType.SECONDLY:
                     RecurrencyInterval.Add(new TimeSpan(0,0,0,r.Interval));
                     break;
                 case Recur.FrequencyType.MINUTELY:
                     RecurrencyInterval.Add(new TimeSpan(0,0,r.Interval,0));
                     break;
                 case Recur.FrequencyType.HOURLY:
                     RecurrencyInterval.Add(new TimeSpan(0,r.Interval,0,0));
                     break;
                 case Recur.FrequencyType.DAILY:
                     RecurrencyInterval.Add(new TimeSpan(r.Interval,0,0,0));
                     break;
                 case Recur.FrequencyType.WEEKLY:
                     RecurrencyInterval.Add(new TimeSpan(r.Interval*7,0,0,0));
                     break;
                 case Recur.FrequencyType.MONTHLY:
                     RecurrencyInterval.Add(new TimeSpan(r.Interval*30,0,0,0));
                     break;
                 case Recur.FrequencyType.YEARLY:
                     RecurrencyInterval.Add(new TimeSpan(r.Interval*356,0,0,0));
                     break;
             }
         }
     }
     return RecurrencyInterval;
 }
 public TimeSpan TimeAvailable()
 {
     var totalTalkDuration = new TimeSpan();
     foreach (var talk in _talks)
     {
         totalTalkDuration = totalTalkDuration.Add(talk.Duration);
     }
     return _maximumDuration.Subtract(totalTalkDuration);
 }
Esempio n. 23
0
 /// <summary>
 /// Получает все время активности Транспортного средства
 /// </summary>
 /// <returns>тип TimeSpan</returns>
 public TimeSpan GetTotalVehicleActivitiesTime()
 {
     TimeSpan totals = new TimeSpan();
     foreach (Vehicle_Activities record in vehicleActivities)
     {
         totals = totals.Add(record.vuActivityDailyData.Get_TotalTimeSpan());
     }
     return totals;
 }
        private static void DurationIsMoreOrLess(TimeSpan expected, TimeSpan actual)
        {
            TimeSpan delta = TimeSpan.FromMilliseconds(100);

            var expectedLower = expected.Subtract(delta);
            var expectedUpper = expected.Add(delta);

            Assert.That(actual, Is.GreaterThanOrEqualTo(expectedLower));
            Assert.That(actual, Is.LessThanOrEqualTo(expectedUpper));
        }
Esempio n. 25
0
 private TimeSpan addBuildLine(TimeSpan total, TimeSpan timeSpent, StringBuilder builder, string state, string project)
 {
     total = total.Add(timeSpent);
     builder.AppendLine(string.Format("{1} build {0} ({2},{3} sec)",
                                      state,
                                      project,
                                      timeSpent.Seconds.ToString(),
                                      timeSpent.Milliseconds.ToString()));
     return total;
 }
Esempio n. 26
0
 protected String getTotalTime()
 {
     TimeSpan totalTime = new TimeSpan(0);
     foreach (GridViewRow row in TimeEntryGridView.Rows)
     {
         TimeSpan span = TimeSpan.Parse(((ITextControl)row.FindControl("TotalTimeLabel")).Text);
         totalTime = totalTime.Add(span);
     }
     return (totalTime.Days * 24 + totalTime.Hours) + " hours " + totalTime.Minutes + " minutes " + totalTime.Seconds + " seconds";
 }
Esempio n. 27
0
 /// <summary>
 /// Calculates the sum of all durations in the given ITaskPhase List.
 /// </summary>
 /// <param name="TaskPhasesList"></param>
 /// <returns></returns>
 public TimeSpan GetTaskPhasesDuration(List<ITaskPhase> TaskPhasesList)
 {
     TimeSpan duration = new TimeSpan(0);
     foreach (var phase in TaskPhasesList)
     {
         var phaseDuration = GetTaskPhaseDuration(phase);
         duration = duration.Add(phaseDuration);
     }
     return duration;
 }
Esempio n. 28
0
        public TimeZoneOperation(PipelineContext context) : base(context) {
            _input = SingleInput();
            _output = context.Field;

            var fromTimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(context.Transform.FromTimeZone);
            _toTimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(context.Transform.ToTimeZone);

            _adjustment = _toTimeZoneInfo.BaseUtcOffset - fromTimeZoneInfo.BaseUtcOffset;
            _daylightAdjustment = _adjustment.Add(new TimeSpan(0, 1, 0, 0));
        }
        private static TimeSpan RoundToNearestMinute(TimeSpan source)
        {
            // there are 10,000 ticks per millisecond, and 1000 milliseconds per second, and 60 seconds per minute
            const int TICKS_PER_MINUTE = 10000 * 1000 * 60;
            var subMinutesComponent = source.Ticks % TICKS_PER_MINUTE;

            return subMinutesComponent < TICKS_PER_MINUTE / 2
                ? source.Subtract(TimeSpan.FromTicks(subMinutesComponent))
                : source.Add(TimeSpan.FromTicks(TICKS_PER_MINUTE - subMinutesComponent));
        }
Esempio n. 30
0
 public static TimeSpan dataTableColumnSumTimeSpanIfTrue(DataTable dataTable, DataColumn dataColumn)
 {
     TimeSpan summationTimespan = new TimeSpan();
     foreach (DataRow dataRow in dataTable.Rows) {
         if ((bool)dataRow["Status"] == true) {
             summationTimespan.Add((TimeSpan)dataRow[dataColumn.ColumnName]);
         }
     }
     return summationTimespan;
 }
Esempio n. 31
0
        public static IHtmlString RelativeDate(this HtmlHelper html, DateTime CompleteDate, int TimeOffset = 0)
        {
            // From http://stackoverflow.com/questions/11/how-do-i-calculate-relative-time/1248#1248
            var ts = new TimeSpan(DateTime.UtcNow.Ticks - CompleteDate.Ticks);
            ts = ts.Add(TimeSpan.FromHours(TimeOffset));
            double delta = ts.TotalSeconds;
            const int SECOND = 1;
            const int MINUTE = 60 * SECOND;
            const int HOUR = 60 * MINUTE;
            const int DAY = 24 * HOUR;
            const int MONTH = 30 * DAY;

            string output;

            if (delta < 1 * MINUTE)
            {
                output = ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
            }
            else if (delta < 2 * MINUTE)
            {
                output = "a minute ago";
            }
            else if (delta < 45 * MINUTE)
            {
                output = ts.Minutes + " minutes ago";
            }
            else if (delta < 90 * MINUTE)
            {
                output = "an hour ago";
            }
            else if (delta < 24 * HOUR)
            {
                output = ts.Hours + " hours ago";
            }
            else if (delta < 48 * HOUR)
            {
                output = "yesterday";
            }
            else if (delta < 30 * DAY)
            {
                output = ts.Days + " days ago";
            }
            else if (delta < 12 * MONTH)
            {
                int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
                output = months <= 1 ? "one month ago" : months + " months ago";
            }
            else
            {
                int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
                output = years <= 1 ? "one year ago" : years + " years ago";
            }

            return new HtmlString(output);
        }
Esempio n. 32
0
        //checks if an entry is in occupied slot
        public static Boolean IsRouteEntryInOccupied(RouteTimeTableEntry entry, FleetAirliner airliner)
        {
            var occupiedSlots1 = AirportHelpers.GetOccupiedSlotTimes(entry.DepartureAirport, airliner.Airliner.Airline);
            var occupiedSlots2 = AirportHelpers.GetOccupiedSlotTimes(entry.Destination.Airport, airliner.Airliner.Airline);

            TimeSpan gateTimeBefore = new TimeSpan(0, 15, 0);
            TimeSpan gateTimeAfter = new TimeSpan(0, 15, 0);

            TimeSpan entryTakeoffTime = new TimeSpan((int)entry.Day, entry.Time.Hours, entry.Time.Minutes, entry.Time.Seconds);
            TimeSpan entryLandingTime = entryTakeoffTime.Add(entry.TimeTable.Route.getFlightTime(entry.Airliner.Airliner.Type));

            if (entryLandingTime.Days > 6)
                entryLandingTime = new TimeSpan(0, entryLandingTime.Hours, entryLandingTime.Minutes, entryLandingTime.Seconds);

            TimeSpan entryStartTakeoffTime = entryTakeoffTime.Subtract(gateTimeBefore);
            TimeSpan entryEndTakeoffTime = entryTakeoffTime.Add(gateTimeAfter);

            TimeSpan tTakeoffTime = new TimeSpan(entryStartTakeoffTime.Days, entryStartTakeoffTime.Hours, (entryStartTakeoffTime.Minutes / 15) * 15, 0);

            while (tTakeoffTime < entryEndTakeoffTime)
            {
                if (occupiedSlots1.Contains(tTakeoffTime))
                    return true;

                tTakeoffTime = tTakeoffTime.Add(new TimeSpan(0, 15, 0));
            }

            TimeSpan entryStartLandingTime = entryLandingTime.Subtract(gateTimeBefore);
            TimeSpan entryEndLandingTime = entryLandingTime.Add(gateTimeAfter);

            TimeSpan tLandingTime = new TimeSpan(entryStartLandingTime.Days, entryStartLandingTime.Hours, (entryStartLandingTime.Minutes / 15) * 15, 0);

            while (tLandingTime < entryEndLandingTime)
            {
                if (occupiedSlots2.Contains(tLandingTime))
                    return true;

                tLandingTime = tLandingTime.Add(new TimeSpan(0, 15, 0));
            }

            return false;
        }
Esempio n. 33
0
 static int Add(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 2);
         System.TimeSpan obj  = (System.TimeSpan)ToLua.CheckObject(L, 1, typeof(System.TimeSpan));
         System.TimeSpan arg0 = (System.TimeSpan)ToLua.CheckObject(L, 2, typeof(System.TimeSpan));
         System.TimeSpan o    = obj.Add(arg0);
         ToLua.PushValue(L, o);
         ToLua.SetBack(L, 1, obj);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Esempio n. 34
0
    IEnumerator reload()
    {
        System.TimeSpan tp = new System.TimeSpan();
        tp.Add(System.TimeSpan.FromMinutes(10));
        Debug.Log("Vou esperar " + 10 * 60 + " para resetar ");
        yield return(new WaitForSeconds(800));

        datamanager dt = GetComponent <datamanager>();

        if (dt.psint < 30 && dt.psint > 0 || dt.sorteando || dt.sorteandojackpot)
        {
            Debug.Log("vou esepera");
            yield return(new WaitForSeconds(100));
        }
        Debug.Log("vou resetar");
        SceneManager.LoadScene(1
                               , LoadSceneMode.Single);
    }
Esempio n. 35
0
    /*
     *  Function: EndSceneTrack
     *
     *  Stops tracking the current scene
     *
     *  See Also:
     *
     *  - <TrackScene>
     */
    public void EndSceneTrack()
    {
        if (curScene != "" && Stats != null && Stats[curScene] != null)
        {
            //Append time
            System.TimeSpan newTime = System.DateTime.Now.Subtract(curSceneStart);

            if (((Hashtable)Stats[curScene])["time_in_scene"] != null)
            {
                newTime = newTime.Add((TimeSpan)((Hashtable)Stats[curScene])["time_in_scene"]);
            }

            ((Hashtable)Stats[curScene])["time_in_scene"] = newTime;

            curScene      = "";
            trackingScene = false;
        }
    }
Esempio n. 36
0
    /*
     *  Function: EndMenuTrack
     *
     *  Stops tracking the current menu. This should be called any time a menu is closed completely. For instance, if you are closing the in-game menu and going back to gameplay. You can just call TrackMenu again if you are switching between menus
     *
     *  See Also:
     *
     *  - <TrackMenu>
     */
    void EndMenuTrack()
    {
        if ((int)curMenu != -1)
        {
            StartSceneTrack();

            System.TimeSpan newTime = new System.TimeSpan(0, 0, 0);

            if (((Hashtable)Stats[curScene])["time_in_" + curMenu.ToString()] != null)
            {
                newTime = (TimeSpan)((Hashtable)Stats[curScene])["time_in_" + curMenu.ToString()];
            }

            newTime.Add(System.DateTime.Now.Subtract(curMenuStart));
            ((Hashtable)Stats[curScene])["time_in_" + curMenu.ToString()] = newTime;

            curMenu = (TimeInMenu)(-1);
        }
    }
Esempio n. 37
0
        private object[] TimeSumm(string[] NormaleMassiveDataTime, string[] EnterExit, string[] KPP, string LastChek, string LastChekEnterExit, string LastChekKPP)
        {
            DateTime TimeEnter = new DateTime();
            DateTime TimeExit  = new DateTime();

            System.TimeSpan SummTime     = new System.TimeSpan();
            System.TimeSpan SummTimeMont = new System.TimeSpan();

            bool BoolExit  = false;
            bool BoolEnter = false;

            DateTime TikDateEnter = new System.DateTime(1996, 6, 3, 22, 15, 0);
            DateTime TikDatelast  = new System.DateTime();

            if (LastChekEnterExit == "Вход")
            {
                BoolEnter   = true;
                TikDatelast = Convert.ToDateTime(LastChek);
                TimeEnter   = Convert.ToDateTime(LastChek);
            }

            for (int i = 0; i < NormaleMassiveDataTime.Length; i++)
            {
                if (EnterExit[i] == "Вход" && LastChekEnterExit == "Выход")
                {
                    TimeEnter         = Convert.ToDateTime(NormaleMassiveDataTime[i]);
                    LastChekEnterExit = "Вход";

                    BoolEnter = true;
                }
                if (EnterExit[i] == "Выход" && LastChekEnterExit == "Вход")
                {
                    TimeExit          = Convert.ToDateTime(NormaleMassiveDataTime[i]);
                    LastChekEnterExit = "Выход";
                    BoolExit          = true;
                }
                if (BoolEnter == true && BoolExit == true)
                {
                    if (TikDatelast.Date == TimeExit.Date)
                    {
                        System.TimeSpan Raznica = TimeExit.Subtract(TimeEnter);
                        SummTime = SummTime.Add(Raznica);

                        TikDatelast = Convert.ToDateTime(NormaleMassiveDataTime);

                        BoolEnter = false;
                        BoolExit  = false;
                    }
                    else
                    {
                        SummTimeMont = SummTimeMont.Add(SummTime);
                        SummTime     = new System.TimeSpan();

                        System.TimeSpan Raznica = TimeExit.Subtract(TimeEnter);
                        SummTime = SummTime.Add(Raznica);

                        TikDatelast = Convert.ToDateTime(NormaleMassiveDataTime);

                        BoolEnter = false;
                        BoolExit  = false;
                    }
                }
            }

            object[] OBJECT = new object[] { };
            return(OBJECT);
        }
Esempio n. 38
0
 /// <summary>
 ///     Adds two TimeSpans.
 /// </summary>
 /// <param name="timeSpan1">A TimeSpan.</param>
 /// <param name="timeSpan2">A TimeSpan.</param>
 /// <returns name="timeSpan">TimeSpan</returns>
 public static System.TimeSpan Add(System.TimeSpan timeSpan1, System.TimeSpan timeSpan2)
 {
     return(timeSpan1.Add(timeSpan2));
 }
Esempio n. 39
0
 /// <summary>
 /// 将TimeSpan偏移指定的秒数
 /// </summary>
 /// <param name="timeSpan"></param>
 /// <returns></returns>
 public static TimeSpan AddSeconds(this TimeSpan timeSpan, int seconds)
 {
     return(timeSpan.Add(new TimeSpan(0, 0, seconds)));
 }
Esempio n. 40
0
 /// <summary>
 /// 将TimeSpan偏移指定的分钟
 /// </summary>
 /// <param name="timeSpan"></param>
 /// <returns></returns>
 public static TimeSpan AddMinutes(this TimeSpan timeSpan, int minutes)
 {
     return(timeSpan.Add(new TimeSpan(0, minutes, 0)));
 }
Esempio n. 41
0
 /// <summary>
 /// 将TimeSpan偏移指定的小时
 /// </summary>
 /// <param name="timeSpan"></param>
 /// <param name="hours"></param>
 /// <returns></returns>
 public static TimeSpan AddHours(this TimeSpan timeSpan, int hours)
 {
     return(timeSpan.Add(new TimeSpan(hours, 0, 0)));
 }
Esempio n. 42
0
    void DoMyWindow(int ID)
    {
        if (windowID == 0)
        {
            // Open Overall Stats Window

            statsSwitch = 0;

            // Draw statistics boxes

            // Total time playing
            GUI.Label(new Rect(50, 50, 300, 140), timeBox);

            // Print overall statistics
            if (LoginScreen.currentID > 0)
            {
                // Calculate overall stats using db.GetColumnValues(patientTable, "Column Name")
                string patientTable = tablePrefix + LoginScreen.currentID;

                // Overall Time
                List <string> timeList = new List <string>();
                timeList = db.GetColumnValues(patientTable, "SessionLength");
                System.TimeSpan timeTotal = System.TimeSpan.Zero;
                foreach (string s in timeList)
                {
                    System.TimeSpan ts = System.TimeSpan.Parse(s);
                    timeTotal = timeTotal.Add(ts);
                }
                string overallTime = timeTotal.ToString();

                // Table showing highest grades for each BBS activity?

                // Print values on drawn boxes
                GUI.Label(new Rect(140, 120, 100, 50), overallTime, summaryStyle);
            }
        }

        else if (windowID == 1)
        {
            // Open Session Stats Window
            if (statsSwitch == 0)
            {
                // Draw any controls inside the window here

                GUI.Label(new Rect(20, 30, 20, 20), "#", colStyle);
                GUI.Label(new Rect(Screen.width / 5, 30, 70, 20), "Date", colStyle);
                GUI.Label(new Rect(Screen.width * 2 / 5, 30, 70, 20), "Time", colStyle);
                GUI.Label(new Rect(Screen.width * 3 / 5, 30, 70, 20), "Duration", colStyle);
                GUI.Label(new Rect(Screen.width * 4 / 5 - 12, 30, 70, 20), "# of Plays", colStyle);

                // show tabular session listing
                GUILayout.BeginArea(new Rect(10, 50, Screen.width - 40, Screen.height - 130));

                if (LoginScreen.currentID > 0)
                {
                    string patientTable = tablePrefix + LoginScreen.currentID;

                    // DISPLAY SESSIONS
                    scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.Height(410));

                    List <int> ID_list = new List <int>();
                    ID_list = db.GetIDValues(patientTable, "SessionID");
                    List <List <string> > listOfRows = new List <List <string> >();
                    listOfRows = db.GetTableValues(patientTable);
                    for (int i = 0; i < ID_list.Count; i++)
                    {
                        List <string> rowList = new List <string>();
                        rowList = listOfRows[i];
                        GUILayout.BeginHorizontal("box");
                        GUILayout.Space(1);
                        GUILayout.Label(rowList[0], idStyle, GUILayout.Width(30));                              // ID
                        GUILayout.FlexibleSpace();
                        GUILayout.Label(rowList[1], normStyle, GUILayout.Width(60));                            // Date
                        GUILayout.FlexibleSpace();
                        GUILayout.Label(rowList[2], normStyle, GUILayout.Width(70));                            // Start Time
                        GUILayout.FlexibleSpace();
                        GUILayout.Label(rowList[3], normStyle, GUILayout.Width(70));                            // Session Length
                        GUILayout.FlexibleSpace();
                        GUILayout.Label(rowList[4], normStyle, GUILayout.Width(20));                            // # of Plays
                        GUILayout.FlexibleSpace();
                        GUILayout.EndHorizontal();
                    }

                    GUILayout.EndScrollView();
                }

                GUILayout.EndArea();
            }

            // Open Play Stats Window
            else if (statsSwitch == 1)
            {
                string patientTable = tablePrefix + LoginScreen.currentID;

                // Draw any controls inside the window here

                GUI.Label(new Rect(50, 40, 100, 30), "BBS Total Score?", normStyle);
                GUI.Label(new Rect(50, 70, 100, 30), "BBS Activity Best Score?", normStyle);

                GUI.Label(new Rect(15, 100, 20, 30), "Play #", colStyle);
                GUI.Label(new Rect(Screen.width / 4 - 18, 100, 50, 30), "Duration", colStyle);
                GUI.Label(new Rect(Screen.width / 2, 100, 100, 30), "Activity", colStyle);
                GUI.Label(new Rect(Screen.width * 3 / 4 - 20, 100, 50, 30), "BBS Grade", colStyle);

                List <string> rowList = new List <string>();
                rowList = db.GetRowValues(patientTable, "SessionID", selectedSession);

                // show tabular play listing
                GUILayout.BeginArea(new Rect(10, 130, Screen.width - 40, Screen.height - 70));

                // DISPLAY PLAYS
                scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.Height(330));

                int numPlays = int.Parse(db.GetValue(patientTable, "NumOfPlays", "SessionID", selectedSession));

                for (int i = 0; i < numPlays; i++)
                {
                    GUILayout.BeginHorizontal("box");
                    GUILayout.Space(10);
                    GUILayout.Label((i + 1).ToString(), idStyle, GUILayout.Width(20));                          // Play #
                    GUILayout.FlexibleSpace();

                    string   play      = rowList[5 + i];
                    string[] playStats = play.Split(line);

                    GUILayout.Label(playStats[0], normStyle, GUILayout.Width(70));                      // Duration
                    GUILayout.FlexibleSpace();

                    GUILayout.Label(playStats[1], normStyle, GUILayout.Width(100));                             // BBS Activity
                    GUILayout.FlexibleSpace();

                    GUILayout.Label(playStats[2], normStyle, GUILayout.Width(40));                              // BBS Grade
                    GUILayout.FlexibleSpace();
                    GUILayout.EndHorizontal();
                }

                GUILayout.EndScrollView();

                GUILayout.EndArea();
            }
        }
    }
Esempio n. 43
0
 /// <summary>
 /// 将TimeSpan偏移指定的天
 /// </summary>
 /// <param name="timeSpan"></param>
 /// <returns></returns>
 public static TimeSpan AddDays(this TimeSpan timeSpan, int days)
 {
     return(timeSpan.Add(new TimeSpan(days, 0, 0, 0)));
 }