本文整理汇总了C#中System.DateTime.AddDays方法的典型用法代码示例。如果您正苦于以下问题:C# DateTime.AddDays方法的具体用法?C# DateTime.AddDays怎么用?C# DateTime.AddDays使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.DateTime
的用法示例。
在下文中一共展示了DateTime.AddDays方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DateAdd
public static DateTime DateAdd(DateInterval Interval, double Number, DateTime DateValue)
{
int years = (int) Math.Round(Conversion.Fix(Number));
switch (Interval)
{
case DateInterval.Year:
return CurrentCalendar.AddYears(DateValue, years);
case DateInterval.Quarter:
return DateValue.AddMonths(years * 3);
case DateInterval.Month:
return CurrentCalendar.AddMonths(DateValue, years);
case DateInterval.DayOfYear:
case DateInterval.Day:
case DateInterval.Weekday:
return DateValue.AddDays((double) years);
case DateInterval.WeekOfYear:
return DateValue.AddDays(years * 7.0);
case DateInterval.Hour:
return DateValue.AddHours((double) years);
case DateInterval.Minute:
return DateValue.AddMinutes((double) years);
case DateInterval.Second:
return DateValue.AddSeconds((double) years);
}
throw new ArgumentException(Utils.GetResourceString("Argument_InvalidValue1", new string[] { "Interval" }));
}
示例2: UpdateTimespan
public void UpdateTimespan ()
{
TodaySpan = DateTime.Today;
YesterdaySpan = TodaySpan.AddDays (-1);
ThisWeekSpan = TodaySpan.AddDays (-((int)DateTime.Now.DayOfWeek));
LastWeekSpan = ThisWeekSpan.AddDays (-7);
}
示例3: CreateTwoWeekPayPeriodIfNotExists
/// <summary>Returns existing payperiod if it exists, otherwise inserts and returns a new payperiod. Throws exception if payperiod overlaps existing payperiod.</summary>
public static PayPeriod CreateTwoWeekPayPeriodIfNotExists(DateTime start){
PayPeriod ppNew=new PayPeriod();
ppNew.DateStart=start;
ppNew.DateStop=start.AddDays(13);
ppNew.DatePaycheck=start.AddDays(16);
//check for identical or overlapping pay periods
PayPeriods.RefreshCache();
foreach(PayPeriod ppInDb in PayPeriods.List) {
if(ppInDb.DateStart == ppNew.DateStart && ppInDb.DateStop == ppNew.DateStop && ppInDb.DatePaycheck == ppNew.DatePaycheck){
//identical pay period already exists.
return ppInDb;
}
//if(pp.DateStart == payP.DateStart && pp.DateStop == payP.DateStop && pp.DatePaycheck != payP.DatePaycheck) {
// //identical pay period already exists, just with a different pay check date.
// //This is a seperate check because it may be important in the future.
// continue;
//}
if(ppInDb.DateStop > ppNew.DateStart && ppInDb.DateStart < ppNew.DateStop) {
//pay periods overlap
throw new Exception("Error inserting pay period. New Pay period overlaps existing pay period.\r\n");
}
}
PayPeriods.Insert(ppNew);
return ppNew;
}
示例4: dealTradMonth
private string dealTradMonth(DateTime now)//用日期計算出交易月份是哪一個月
{
// 本月第一天
DateTime firstDay = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1, 0, 0, 0);
// 找到第一個星期三
int wk;//星期幾
wk = int.Parse(firstDay.DayOfWeek.ToString("d"));
while (wk != 3)
{
firstDay = firstDay.AddDays(1);
wk = (wk + 1) % 7;
}
DateTime thridWeekWendesday = firstDay.AddDays(14);
if (now.Day > thridWeekWendesday.Day)
{
return Convert.ToString(now.Month + 1);
}
else
{
return Convert.ToString(now.Month);
}
}//end dealTradMonth
示例5: EndOfWeek_SendDate
public void EndOfWeek_SendDate()
{
var baseDate = DateTime.Now;
var expectedDate = new DateTime(baseDate.Year, baseDate.Month, baseDate.Day, 23, 59, 59, 999, baseDate.Kind);
var lastWeekDay = DevUtils.DateTimeExtensions.BaseDateTimeExtensions.GetDefaultLastWeekDay();
var lastWeekBusiness = DevUtils.DateTimeExtensions.BaseDateTimeExtensions.GetDefaultLastWeekBusinessDay();
while (true)
{
if (expectedDate.DayOfWeek == lastWeekDay)
break;
expectedDate = (int)lastWeekDay > (int)expectedDate.DayOfWeek
? expectedDate.AddDays(1)
: expectedDate.AddDays(-1);
}
Assert.AreEqual(expectedDate, baseDate.EndOfWeek(), "Error getting end of week");
lastWeekDay = DayOfWeek.Thursday;
DevUtils.DateTimeExtensions.BaseDateTimeExtensions.SetDefaultLastDay(lastWeekDay, lastWeekBusiness);
expectedDate = new DateTime(baseDate.Year, baseDate.Month, baseDate.Day, 23, 59, 59, 999, baseDate.Kind);
while (true)
{
if (expectedDate.DayOfWeek == lastWeekDay)
break;
expectedDate = (int)lastWeekDay > (int)expectedDate.DayOfWeek
? expectedDate.AddDays(1)
: expectedDate.AddDays(-1);
}
Assert.AreEqual(expectedDate, baseDate.EndOfWeek(), "Error getting end of week");
}
示例6: OnPrePublish
public override bool OnPrePublish(IWin32Window dialogOwner, IProperties properties,
IPublishingContext publishingContext, bool publish)
{
var info = (BlogPost) publishingContext.PostInfo;
//look at the publish date.
if (!info.HasDatePublishedOverride)
{
var nextPubDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
nextPubDate = GetNextDayOccurrence(DayOfWeek.Tuesday, nextPubDate);
var reader = new JsonTextReader(reader: File.OpenText("Plugins\\Throttle.json"));
var json = new Newtonsoft.Json.JsonSerializer();
var config = json.Deserialize<Configuration>(reader);
var wrapper = new MetaWeblogWrapper(config.Url, config.Username, config.Password);
List<Post> recentPosts = wrapper.GetRecentPosts(10).ToList();
while (recentPosts.Any(p => p.DateCreated >= nextPubDate && p.DateCreated < nextPubDate.AddDays(1)))
{
nextPubDate = GetNextDayOccurrence(DayOfWeek.Tuesday, nextPubDate.AddDays(1));
}
var pubDate = new DateTime(nextPubDate.Year, nextPubDate.Month, nextPubDate.Day, 9, 0, 0);
info.DatePublished = pubDate;
info.DatePublishedOverride = pubDate;
}
return base.OnPrePublish(dialogOwner, properties, publishingContext, publish);
}
示例7: GetTasks
private ObservableCollection<GanttBaselineTask> GetTasks(DateTime date)
{
var ganttAPI = new GanttBaselineTask()
{
Start = date,
End = date.AddDays(2),
Title = "Design public API",
Description = "Description: Design public API",
StartPlannedDate = date.AddDays(1),
EndPlannedDate = date.AddDays(2.5)
};
var ganttRendering = new GanttBaselineTask()
{
Start = date.AddDays(2).AddHours(8),
End = date.AddDays(4),
Title = "Gantt Rendering",
Description = "Description: Gantt Rendering",
StartPlannedDate = date.AddDays(3),
EndPlannedDate = date.AddDays(3).AddHours(12)
};
var ganttDemos = new GanttBaselineTask()
{
Start = date.AddDays(4.5),
End = date.AddDays(7),
Title = "Gantt Demos",
Description = "Description: Gantt Demos",
StartPlannedDate = date.AddDays(5),
EndPlannedDate = date.AddDays(6)
};
var milestone = new GanttBaselineTask()
{
Start = date.AddDays(7),
End = date.AddDays(7).AddHours(1),
Title = "Review",
Description = "Description: Review",
IsMilestone = true,
StartPlannedDate = date.AddDays(7),
EndPlannedDate = date.AddDays(7).AddHours(15)
};
ganttRendering.Dependencies.Add(new Dependency() { FromTask = ganttAPI });
ganttDemos.Dependencies.Add(new Dependency() { FromTask = ganttRendering });
var iterationTask = new GanttBaselineTask()
{
Start = date,
End = date.AddDays(7),
Title = "Iteration 1",
Children = { ganttAPI, ganttRendering, ganttDemos, milestone },
StartPlannedDate = date
};
var iterationTaskEndPlannedDate = GetInterationPlannedDateEnd(iterationTask.Children, date);
iterationTask.EndPlannedDate = iterationTaskEndPlannedDate;
ObservableCollection<GanttBaselineTask> tasks = new ObservableCollection<GanttBaselineTask>() { iterationTask };
return tasks;
}
示例8: GetNextWakeupTime
public DateTime GetNextWakeupTime(DateTime earliestWakeupTime)
{
IPowerScheduler ps = GlobalServiceProvider.Instance.Get<IPowerScheduler>();
EPGWakeupConfig cfg = ps.Settings.GetSetting("RebootConfig").Get<EPGWakeupConfig>();
DateTime now = DateTime.Now;
// The earliest wakeup time cannot be in the past
if (earliestWakeupTime < now)
earliestWakeupTime = now;
// Start with the earliest possible day
DateTime nextRun = new DateTime(earliestWakeupTime.Year, earliestWakeupTime.Month, earliestWakeupTime.Day, cfg.Hour, cfg.Minutes, 0);
// If the wakeup time is before the earliest wakeup time or if there already was a reboot on this day then take the next day
if (nextRun < earliestWakeupTime || cfg.LastRun.Date >= nextRun.Date)
nextRun = nextRun.AddDays(1);
// Try the next 7 days
for (int i = 0; i < 7; i++)
{
// Check if this day is configured for reboot
if (ShouldRun(cfg.Days, nextRun.DayOfWeek))
return nextRun;
nextRun = nextRun.AddDays(1);
}
// Found no day configured for reboot
return DateTime.MaxValue;
}
示例9: GenerateCorpTriMonday
public void GenerateCorpTriMonday(DateTime generateDate)
{
DateTime ReprtStartDate = generateDate.AddDays(-9);
DateTime ReprtEndDate = generateDate.AddDays(-3);
string[] ProcNamesW = new string[5] { "Corp_IM", "Corp_SR", "Corp_PBI", "Corp_PKE", "Corp_WO" };
string[,] ParamsW = new string[5, 2] {
{ ReprtStartDate.ToString("yyyy-MM-dd"), ReprtEndDate.ToString("yyyy-MM-dd") }
,{ ReprtStartDate.ToString("yyyy-MM-dd"), ReprtEndDate.ToString("yyyy-MM-dd") }
,{ ReprtStartDate.ToString("yyyy-MM-dd"), ReprtEndDate.ToString("yyyy-MM-dd") }
,{ ReprtStartDate.ToString("yyyy-MM-dd"), ReprtEndDate.ToString("yyyy-MM-dd") }
,{ ReprtStartDate.ToString("yyyy-MM-dd"), ReprtEndDate.ToString("yyyy-MM-dd") }
};//benchmark para add in ExecuteProcWithParam method
string[] sheetnameW = new string[5] { "IM", "SR", "PBI", "PKE", "WO" };
string templateReportfile = "Corp Tricare Weekly New -demo.xls";
DBAccess dbAccess = new DBAccess();
DataSet CorpDs = dbAccess.ExecuteProcWithParam_Navy(templateReportfile, ProcNamesW, sheetnameW, ParamsW, ReprtEndDate);
string reportStartStr = ReprtStartDate.ToString("MMdd");
string reportEndStr = ReprtEndDate.ToString("MMdd");
ExcelBus excelBiz = new ExcelBus();
string savePath = corpTrackWeekly1Path + reportStartStr + "-" + reportEndStr;
string corpReportSavePath = savePath + @"\Corp Tricare Weekly New " + reportStartStr + "-" + reportEndStr + ".xls";
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
excelBiz.ExportDataToExcel_New(corpReportSavePath, templateReportfile, ProcNamesW, sheetnameW, CorpDs);
}
示例10: Next
public JsonResult Next(int no, int locationId)
{
today = today.AddDays(no);
GetDate();
GetMonth();
period = string.Format("{0}{1}", today.Year, bulan);
IList<TenantSubterminalDailySales> dailySales = subTerminalRepo.FindTenantSubTerminalDailySaleByPeriod(today, locationId);
var _previousDayDate = today.AddDays(-1);
var _twoDaysBeforeDate = today.AddDays(-2);
IList<TenantSubterminalDailySales> previousDay = subTerminalRepo.FindTenantSubTerminalDailySaleByPeriod(_previousDayDate, locationId);
IList<TenantSubterminalDailySales> twoDaysBefore = subTerminalRepo.FindTenantSubTerminalDailySaleByPeriod(_twoDaysBeforeDate, locationId);
SalesAmountDay salesAmount = new SalesAmountDay()
{
CompanyName = "",
LocationId = locationId,
TotalSaleIDR = subTerminalRepo.TotalTenanSubTerminalSalePerDay(dailySales).ToString("N"),
TotalSaleUSD = dailySales.Sum<TenantSubterminalDailySales>(y => y.TotalSalesPerTenantInUSD).ToString("N"),
Transactiondate = today.ToString("dd MMMM yyyy"),
PreviousDay = _previousDayDate.ToString("dd MMMM yyyy"),
TwoDaysBefore = _twoDaysBeforeDate.ToString("dd MMMM yyyy"),
TotalSaleIDRPreviousDay = previousDay.Sum<TenantSubterminalDailySales>(y => y.TotalSalePerTenan).ToString("N"),
TotalSaleUSDPreviousDay = previousDay.Sum<TenantSubterminalDailySales>(y => y.TotalSalesPerTenantInUSD).ToString("N"),
TotalSaleIDRTwoDaysBefore = twoDaysBefore.Sum<TenantSubterminalDailySales>(y => y.TotalSalePerTenan).ToString("N"),
TotalSaleUSDTwoDaysBefore = twoDaysBefore.Sum<TenantSubterminalDailySales>(y => y.TotalSalesPerTenantInUSD).ToString("N")
};
return Json(salesAmount, JsonRequestBehavior.AllowGet);
}
示例11: CreateWeeklyStatReportFor
private void CreateWeeklyStatReportFor(string connectionString,string sqlQuery,string reportName)
{
startingTime = new DateTime(Year, UnixTimeStampUtility.GetMonthNumber(Month), 01); //initialize to day 01 of the given month.
DateTime monthEndTime = new DateTime(Year, UnixTimeStampUtility.GetMonthNumber(Month), UnixTimeStampUtility.GetDaysInMonth(Month));
List<Tuple<string, string>> uploadsDataPoints = new List<Tuple<string, string>>();
int week = 1;
using (var sqlConnection = new SqlConnection(connectionString))
{
using (var dbExecutor = new SqlExecutor(sqlConnection))
{
sqlConnection.Open();
while (startingTime <= monthEndTime)
{
DateTime endTime = startingTime.AddDays(7);
if (endTime > monthEndTime) endTime = monthEndTime;
try
{
var count = dbExecutor.Query<Int32>(string.Format(sqlQuery, startingTime.ToString("yyyy-MM-dd"), endTime.ToString("yyyy-MM-dd"))).SingleOrDefault();
uploadsDataPoints.Add(new Tuple<string, string>("Week" + week++, count.ToString()));
}
catch (NullReferenceException)
{
uploadsDataPoints.Add(new Tuple<string, string>("Week" + week++, "0"));
}
startingTime = startingTime.AddDays(7);
}
}
}
JArray reportObject = ReportHelpers.GetJson(uploadsDataPoints);
ReportHelpers.CreateBlob(ReportStorage, reportName + Month + "MonthlyReport.json", "dashboard", "application/json", ReportHelpers.ToStream(reportObject));
}
示例12: RemoveWeekendDays
static void RemoveWeekendDays(ref DateTime start, ref DateTime end)
{
if (start.DayOfWeek == DayOfWeek.Saturday) start = start.AddDays(2);
if (start.DayOfWeek == DayOfWeek.Sunday) start = start.AddDays(1);
if (end.DayOfWeek == DayOfWeek.Saturday) end = end.AddDays(-1);
if (end.DayOfWeek == DayOfWeek.Sunday) end = end.AddDays(-2);
}
示例13: BuildReport
private static void BuildReport()
{
string connectionString = ThemeRepositoryFactory.Default.ConnectionProvider.GetWriteConnectionString();
//获取当前报表统计表中已经统计到的日期
DateTime lastDate = new DateTime(2010, 5, 22);
string cmdText = "SELECT MAX(ReportDate) FROM VisitorsDayReport";
object result = SqlHelper.ExecuteScalar(connectionString, System.Data.CommandType.Text, cmdText);
if (result != DBNull.Value && Convert.ToInt32(result) > 0)
{
lastDate = DateTime.ParseExact(result.ToString(), "yyyyMMdd", null).AddDays(1);
}
//开始统计从上个统计日到今天的所有数据
while (lastDate < DateTime.Now.Date)
{
cmdText = string.Format(CMD_ALL_USER_COUNT, lastDate.ToString("yyyyMMdd"), lastDate.AddDays(1).ToString("yyyyMMdd"));
int allUserCount = Convert.ToInt32(SqlHelper.ExecuteScalar(connectionString, System.Data.CommandType.Text, cmdText));
cmdText = string.Format(CMD_OLD_USER_COUNT, lastDate.ToString("yyyyMMdd"), lastDate.AddDays(1).ToString("yyyyMMdd"));
int oldUserCount = Convert.ToInt32(SqlHelper.ExecuteScalar(connectionString, System.Data.CommandType.Text, cmdText));
cmdText = string.Format(CMD_INSERT_REPORT_DATA
, allUserCount
, oldUserCount
, lastDate.ToString("yyyyMMdd")
);
SqlHelper.ExecuteNonQuery(connectionString, System.Data.CommandType.Text, cmdText);
Console.WriteLine(string.Format("计算完成{0}日的统计,所有用户:{1},老用户:{2}", lastDate, allUserCount, oldUserCount));
lastDate = lastDate.AddDays(1);
}
}
示例14: GetAlgorithmPerformance
/// <summary>
/// Returns the performance of the algorithm in the specified date range
/// </summary>
/// <param name="fromDate">The initial date of the range</param>
/// <param name="toDate">The final date of the range</param>
/// <param name="trades">The list of closed trades</param>
/// <param name="profitLoss">Trade record of profits and losses</param>
/// <param name="equity">The list of daily equity values</param>
/// <param name="pointsPerformance">The list of algorithm performance values</param>
/// <param name="pointsBenchmark">The list of benchmark values</param>
/// <param name="startingCapital">The algorithm starting capital</param>
/// <returns>The algorithm performance</returns>
private static AlgorithmPerformance GetAlgorithmPerformance(
DateTime fromDate,
DateTime toDate,
List<Trade> trades,
SortedDictionary<DateTime, decimal> profitLoss,
SortedDictionary<DateTime, decimal> equity,
List<ChartPoint> pointsPerformance,
List<ChartPoint> pointsBenchmark,
decimal startingCapital)
{
var periodTrades = trades.Where(x => x.ExitTime.Date >= fromDate && x.ExitTime < toDate.AddDays(1)).ToList();
var periodProfitLoss = new SortedDictionary<DateTime, decimal>(profitLoss.Where(x => x.Key >= fromDate && x.Key.Date < toDate.AddDays(1)).ToDictionary(x => x.Key, y => y.Value));
var periodEquity = new SortedDictionary<DateTime, decimal>(equity.Where(x => x.Key.Date >= fromDate && x.Key.Date < toDate.AddDays(1)).ToDictionary(x => x.Key, y => y.Value));
var listPerformance = new List<double>();
var performance = ChartPointToDictionary(pointsPerformance, fromDate, toDate);
performance.Values.ToList().ForEach(i => listPerformance.Add((double)(i / 100)));
var benchmark = ChartPointToDictionary(pointsBenchmark, fromDate, toDate);
var listBenchmark = CreateBenchmarkDifferences(benchmark, periodEquity);
EnsureSameLength(listPerformance, listBenchmark);
var runningCapital = equity.Count == periodEquity.Count ? startingCapital : periodEquity.Values.FirstOrDefault();
return new AlgorithmPerformance(periodTrades, periodProfitLoss, periodEquity, listPerformance, listBenchmark, runningCapital);
}
示例15: AggregatesPeriodInCountModeWithDailyData
public void AggregatesPeriodInCountModeWithDailyData()
{
TradeBar consolidated = null;
var period = TimeSpan.FromDays(1);
var consolidator = new TradeBarConsolidator(2);
consolidator.DataConsolidated += (sender, bar) =>
{
consolidated = bar;
};
var reference = new DateTime(2015, 04, 13);
consolidator.Update(new TradeBar { Time = reference, Period = period});
Assert.IsNull(consolidated);
consolidator.Update(new TradeBar { Time = reference.AddDays(1), Period = period });
Assert.IsNotNull(consolidated);
Assert.AreEqual(TimeSpan.FromDays(2), consolidated.Period);
consolidated = null;
consolidator.Update(new TradeBar { Time = reference.AddDays(2), Period = period });
Assert.IsNull(consolidated);
consolidator.Update(new TradeBar { Time = reference.AddDays(3), Period = period });
Assert.IsNotNull(consolidated);
Assert.AreEqual(TimeSpan.FromDays(2), consolidated.Period);
}