本文整理汇总了C#中System.TimeSpan.Add方法的典型用法代码示例。如果您正苦于以下问题:C# TimeSpan.Add方法的具体用法?C# TimeSpan.Add怎么用?C# TimeSpan.Add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.TimeSpan
的用法示例。
在下文中一共展示了TimeSpan.Add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TryGetFromNaturalFormat
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;
}
示例2: ConvertStringToTimeSpan
/// <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;
}
示例3: ParseTime
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;
}
示例4: Parse
/// <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;
}
示例5: GetGreenTimeAboveSpeed
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;
}
示例6: Delay
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));
}
示例7: DetailsView1_ItemCreated
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;
}
}
示例8: PrintDayStats
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));
}
示例9: BuildInvoice
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;
}
示例10: RemindStartOfWeek
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);
}
}
}
示例11: SetTimer
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;
}
}
示例12: InListOutOfList
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));
}
}
示例13: RemindEndOfWeek
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!
}
}
}
示例14: Connect
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);
}
}
示例15: TryParse
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;
}