本文整理汇总了C#中System.DateTime.Subtract方法的典型用法代码示例。如果您正苦于以下问题:C# DateTime.Subtract方法的具体用法?C# DateTime.Subtract怎么用?C# DateTime.Subtract使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.DateTime
的用法示例。
在下文中一共展示了DateTime.Subtract方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetPercentTime
/// <summary>
/// Returns a percentage of time elapsed from the assigned date to the due date
/// </summary>
/// <param name="assignedOn">Date assigned</param>
/// <param name="dueOn">Date due</param>
/// <returns>Normalized percent</returns>
public static double GetPercentTime(DateTime assignedOn, DateTime dueOn)
{
TimeSpan totalTime = dueOn.Subtract(assignedOn);
TimeSpan timeLeft = dueOn.Subtract(DateTime.Now);
TimeSpan timeElapsed = totalTime.Subtract(timeLeft);
return ((double) timeElapsed.Ticks / totalTime.Ticks);
}
示例2: Main
static void Main()
{
DateTime start = new DateTime(2012, 1, 14);
DateTime end = new DateTime(2013, 1, 25);
if(start>end)
{
DateTime temp;
temp = start;
start = end;
end = temp;
}
DateTime[] myDays = new DateTime[(int)end.Subtract(start).TotalDays];
int daysToSubstract = 0;
for (DateTime i = start; i <=end; )
{
for (int j = 0; j < holidays.Length; j++)
{
if(i==holidays[j])
{
daysToSubstract++;
}
}
if (i.DayOfWeek.ToString() == "Saturday" || i.DayOfWeek.ToString() == "Sunday")
{
daysToSubstract++;
}
i=i.AddDays(1);
}
Console.WriteLine("There are {0} days between {1:dd.MMMM.yyyy} and {2:dd.MMMM.yyyy}", end.Subtract(start).TotalDays,start,end);
Console.WriteLine("{0} of these days are either a holiday or a weekend day",daysToSubstract);
Console.WriteLine("So the total amount of work days is: {0}", end.Subtract(start).TotalDays-daysToSubstract);
}
示例3: KeyPerformanceIndicators
public ActionResult KeyPerformanceIndicators(DateTime date)
{
dynamic data = new ExpandoObject();
var orderVolume = salesDataWarehouseService.OrderVolume(date, date.Subtract(TimeSpan.FromDays(SalesHistoryDayRange)));
data.RecentOrders = new ExpandoObject();
data.RecentOrders.CurrentValue = orderVolume.Values.LastOrDefault();
data.RecentOrders.HistoricalValues = orderVolume.Values.ToArray();
var averageOrderValue = salesDataWarehouseService.AverageOrderValue(date, date.Subtract(TimeSpan.FromDays(SalesHistoryDayRange)));
data.AverageOrderValue = new ExpandoObject();
data.AverageOrderValue.CurrentValue = averageOrderValue.Values.LastOrDefault();
data.AverageOrderValue.HistoricalValues = averageOrderValue.Values.ToArray();
var uniqueCustomers = salesDataWarehouseService.UniqueCustomers(date, date.Subtract(TimeSpan.FromDays(SalesHistoryDayRange)));
data.NewCustomerRatio = new ExpandoObject();
data.NewCustomerRatio.CurrentValue = uniqueCustomers.Values.LastOrDefault().Item2;
data.NewCustomerRatio.HistoricalValues = uniqueCustomers.Values.ToList().ConvertAll(item => item.Item1).ToArray();
data.NewCustomerRatio.HistoricalUniqueCustomerValues = uniqueCustomers.Values.ToList().ConvertAll(item => item.Item2).ToArray();
var uniqueSiteVisitors = salesDataWarehouseService.UniqueSiteVisitors(date, date.Subtract(TimeSpan.FromDays(SalesHistoryDayRange)));
data.UniqueSiteVisitors = new ExpandoObject();
data.UniqueSiteVisitors.CurrentValue = uniqueSiteVisitors.Values.LastOrDefault();
data.UniqueSiteVisitors.HistoricalValues = uniqueSiteVisitors.Values.ToArray();
return new JsonNetResult()
{
Data = data,
HttpStatusCode = (int)System.Net.HttpStatusCode.OK,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
示例4: GetClosestIndexByDate
private int GetClosestIndexByDate(MarketSeries series, DateTime time)
{
var lastIndex = series.Close.Count - 1;
if (time >= series.OpenTime[lastIndex])
return lastIndex;
var timeDifference = time.Subtract(series.OpenTime[0]);
int index = 0;
for (int i = 0; i < lastIndex - 1; i++)
{
if (time < series.OpenTime[i])
break;
var currDiff = time.Subtract(series.OpenTime[i]);
if (currDiff < timeDifference)
{
timeDifference = currDiff;
index = i;
}
}
return index;
}
示例5: OutputDebugStringEventArgs
internal OutputDebugStringEventArgs(int processId, DateTime messageTime, string messageText) {
ProcessId = processId;
MessageTime = messageTime;
Message = messageText;
SinceFirstEvent = messageTime.Subtract(Process.FirstMessageTime);
SinceProcessStarted = messageTime.Subtract(Process.StartTime);
}
示例6: PrepareInputSeries_ThreeSeries_LastOne_StartsLater
public void PrepareInputSeries_ThreeSeries_LastOne_StartsLater()
{
TripletAnalyser tripletAnalyser = new TripletAnalyser();
IList<string> symbolList = new List<string>();
DateTime minDate = new DateTime(2000, 1, 1);
DateTime maxDate = new DateTime(2001, 1, 1);
string exchange = "Exchange";
string symbol = "Symbol_1";
IStoreOHLCVIntervals intervalRepository = MockRepository.GenerateStub<IStoreOHLCVIntervals>();
intervalRepository.Stub(r => r.GetByTimeSpan(exchange, symbol, minDate, maxDate))
.Return(GenerateInputSeriesList(symbol, minDate, maxDate.Subtract(minDate).Days));
symbol = "Symbol_2";
intervalRepository.Stub(r => r.GetByTimeSpan(exchange, symbol, minDate, maxDate))
.Return(GenerateInputSeriesList(symbol, minDate, maxDate.Subtract(minDate).Days));
symbol = "Symbol_3";
intervalRepository.Stub(r => r.GetByTimeSpan(exchange, symbol, minDate, maxDate))
.Return(GenerateInputSeriesList(symbol, minDate.AddDays(10), maxDate.Subtract(minDate).Days));
List<double[]> intersection = tripletAnalyser.PrepareInputSeries(new List<string>() { "Exchange:Symbol_1", "Exchange:Symbol_2", "Exchange:Symbol_3" }, minDate, maxDate, intervalRepository);
Assert.AreEqual(3, intersection.Count);
Assert.AreEqual(356, intersection[0].Length);
Assert.AreEqual(356, intersection[1].Length);
Assert.AreEqual(356, intersection[2].Length);
Assert.LessOrEqual(Double.Epsilon, Math.Abs(minDate.AddDays(10).Ticks - intersection[0][0]));
Assert.LessOrEqual(Double.Epsilon, Math.Abs(maxDate.Ticks - intersection[0][355]));
}
示例7: DataAt
public ThinkGearData DataAt(double secondsFromBeginning)
{
currentTime = DateTime.Now;
deltaSeconds = currentTime.Subtract(startTime).TotalSeconds;
elapsedSeconds += currentTime.Subtract(lastFrameTime).TotalSeconds;
if(elapsedSeconds > BLINK_PERIOD){
blinkValue = (int)(256.0f * (float)r.NextDouble());
elapsedSeconds -= BLINK_PERIOD;
}
lastFrameTime = currentTime;
return new ThinkGearData(secondsFromBeginning,
(int)(Math.Sin(deltaSeconds / 3.0f) * 50.0f + 50.0f),
(int)(Math.Cos(deltaSeconds / 3.0f) * 50.0f + 50.0f),
(int)(Math.Sin(deltaSeconds / 7.0f) * 50.0f + 50.0f),
0,
RandomValue(), RandomValue(),
RandomValue(), RandomValue(),
RandomValue(), RandomValue(),
RandomValue(), RandomValue(),
512.0f * (float)r.NextDouble(),
blinkValue);
}
示例8: Main
static void Main(string[] args)
{
var d = new DateTime(1970, 1, 1);
var unspecified = new DateTime(d.Ticks, DateTimeKind.Unspecified);
var local = new DateTime(d.Ticks, DateTimeKind.Local);
var localInUtc = DateTime.SpecifyKind(local, DateTimeKind.Utc);
var utc = new DateTime(d.Ticks, DateTimeKind.Utc);
Debug.WriteLine("un as local: " + unspecified.ToLocalTime().ToLongTimeString());
Debug.WriteLine("lo as local: " + local.ToLocalTime().ToLongTimeString());
Debug.WriteLine("ut as local: " + utc.ToLocalTime().ToLongTimeString());
Debug.WriteLine("un as utc: " + unspecified.ToUniversalTime().ToLongTimeString());
Debug.WriteLine("lo as utc: " + local.ToUniversalTime().ToLongTimeString());
Debug.WriteLine("ut as utc: " + utc.ToUniversalTime().ToLongTimeString());
TimeSpan ts = unspecified.Subtract(local);
ts = unspecified.Subtract(utc);
ts = local.Subtract(utc);
local = DateTime.SpecifyKind(d, DateTimeKind.Local);
utc = DateTime.SpecifyKind(d, DateTimeKind.Utc);
var unspecifiedTicks = unspecified.Ticks;
var localTicks = local.Ticks;
var utcTicks = utc.Ticks;
}
示例9: ToUnsignedDbTicks
public static ulong ToUnsignedDbTicks(DateTime d)
{
long dt = d.Subtract(JS_EPOCH).Ticks;
if (dt < 0)
{
throw new Exception("Unsigned dbticks is negative");
}
return (ulong)(0.0001 * d.Subtract(JS_EPOCH).Ticks);
}
示例10: GetCurrentIntervalTime
public static DateTime GetCurrentIntervalTime(DateTime lastTime, DateTime newTime, Interval interval)
{
if (newTime.Subtract(lastTime) < AppConst.AppTimeSpans[interval])
{
return lastTime;
}
else
{
while (newTime.Subtract(lastTime) >= AppConst.AppTimeSpans[interval])
{
lastTime = lastTime.Add(AppConst.AppTimeSpans[interval]);
}
return lastTime;
}
}
示例11: Calculate
public void Calculate(){
//define time points:
startTime = new System.DateTime(1,1,1,(int)minValue,0,0,0);
endTime = new System.DateTime(1,1,1,(int)maxValue,0,0,0);
//correct 24 hour loop around:
if (endTime.Subtract(startTime).Hours == 23) {
endTime = startTime.AddDays(1);
}else{
endTime = endTime.AddHours(1);
}
//calculate duration:
duration = endTime.Subtract(startTime);
}
示例12: Before
/// <summary>
/// Asserts that a <see cref="DateTime"/> occurs a specified amount of time before another <see cref="DateTime"/>.
/// </summary>
/// <param name="target">
/// The <see cref="DateTime"/> to compare the subject with.
/// </param>
/// <param name="because">
/// A formatted phrase explaining why the assertion should be satisfied. If the phrase does not
/// start with the word <i>because</i>, it is prepended to the message.
/// </param>
/// <param name="reasonArgs">
/// Zero or more values to use for filling in any <see cref="string.Format(string,object[])"/> compatible placeholders.
/// </param>
public AndConstraint<DateTimeAssertions> Before(DateTime target, string because = "",
params object[] reasonArgs)
{
bool success = Execute.Assertion
.ForCondition(subject.HasValue)
.BecauseOf(because, reasonArgs)
.FailWith("Expected date and/or time {0} to be " + predicate.DisplayText +
" {1} before {2}{reason}, but found a <null> DateTime.",
subject, timeSpan, target);
if (success)
{
var actual = target.Subtract(subject.Value);
if (!predicate.IsMatchedBy(actual, timeSpan))
{
Execute.Assertion
.BecauseOf(because, reasonArgs)
.FailWith(
"Expected date and/or time {0} to be " + predicate.DisplayText +
" {1} before {2}{reason}, but it differs {3}.",
subject, timeSpan, target, actual);
}
}
return new AndConstraint<DateTimeAssertions>(parentAssertions);
}
示例13: DateMinueDiff
/// <summary>
/// 时间段比较,返回已分钟为单位
/// </summary>
/// <param name="DateTime1"></param>
/// <param name="DateTime2"></param>
/// <returns></returns>
public static string DateMinueDiff(DateTime DateTime1, DateTime DateTime2)
{
string dateDiff = "";
TimeSpan ts = DateTime1.Subtract(DateTime2);
dateDiff = ts.TotalMinutes.ToString();
return dateDiff;
}
示例14: AddActivityLog
public bool AddActivityLog(int userID, DateTime date)
{
try
{
int discount = 0;
UserActivityLog log = new UserActivityLog();
if (log.GetLastActivityByUserID(userID))
{
// get between days only i.e.
// last day 01/03/2015 - current date 04/03/2015
// the between days not equal 3 it's only 2 ( 02/03/2015 - 03-03-2015 )
// so diff = current date - last date - 1
discount = date.Subtract(log.Date).Days - 1;
}
log.AddNew();
log.ComboUserID = userID;
log.Date = date;
log.DaysToDiscount = discount;
log.Save();
// if save success
return true;
}
catch (Exception ex)
{
//if save fail - duplicate entry
return false;
}
}
示例15: GetBaseUnit
private BaseUnit GetBaseUnit(DateTime dateFrom, DateTime dateTo)
{
var diff = dateTo.Subtract(dateFrom);
var days = diff.TotalDays;
var result = BaseUnit.Years;
// Try to maintain groups count below TARGET_RESULT_SIZE
if (diff.TotalMinutes < TARGET_RESULT_SIZE)
{
result = BaseUnit.Minutes;
}
else if (diff.TotalHours < TARGET_RESULT_SIZE)
{
result = BaseUnit.Hours;
}
else if (days < TARGET_RESULT_SIZE)
{
result = BaseUnit.Days;
}
else if (days / DAYS_PER_WEEK < TARGET_RESULT_SIZE)
{
result = BaseUnit.Weeks;
}
else if (days / DAYS_PER_MONTH < TARGET_RESULT_SIZE)
{
result = BaseUnit.Months;
}
return result;
}