System.DateTime.AddMonths(int)

Here are the examples of the csharp api System.DateTime.AddMonths(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

765 Examples 7

19 View Source File : FakerGenerator.cs
License : MIT License
Project Creator : alfa-laboratory

public DateTime? GetDate(int day, int month, int year, bool future = true, DateTime? refDate = null)
        {
            var trigger = 1;
            if (!future) trigger = -1;

            refDate ??= DateTimeHelper.Value.GetDateTimeNow();

            if (day >= 0 && month >= 0 && year >= 0)
            {
                try
                {
                    return refDate?
                        .AddDays((trigger) * day)
                        .AddMonths((trigger) * month)
                        .AddYears((trigger) * year);
                }catch(ArgumentOutOfRangeException ex)
                {
                    Log.Logger().LogWarning($"Date {day}.{month}.{year} is incorrect. Exception is {ex.Message}");
                    return null;
                }
            }
            Log.Logger().LogWarning($"Use only positive numbers when specifying a date other than the specified date.");
            return null;
        }

19 View Source File : DateImplementation.cs
License : MIT License
Project Creator : apexsharp

public Date addMonths(int months) => new DateInstance(date.AddMonths(months));

19 View Source File : DateTimeExtensions.cs
License : MIT License
Project Creator : Adoxio

public static DateTime Round(this DateTime d, RoundTo to)
		{
			var floor = Floor(d, to);
			if (to == RoundTo.Second && d.Millisecond >= 500) return floor.AddSeconds(1);
			if (to == RoundTo.Minute && d.Second >= 30) return floor.AddMinutes(1);
			if (to == RoundTo.Hour && d.Minute >= 30) return floor.AddHours(1);
			if (to == RoundTo.Day && d.Hour >= 12) return floor.AddDays(1);
			if (to == RoundTo.Month && d.Day >= DateTime.DaysInMonth(d.Year, d.Month) / 2) return floor.AddMonths(1);
			return d;
		}

19 View Source File : JwtToken.cs
License : MIT License
Project Creator : AleksandreJavakhishvili

private static Func<Claim[], string> Encode(string issuer, string audience, string key, DateTime? expireDate = null)
        {
            return claims =>
            {
                var credentials = new SigningCredentials(SecurityKey(key), SecurityAlgorithms.HmacSha256);

                var securityToken = new JwtSecurityToken(issuer, audience, claims, null, expireDate ?? DateTime.Now.AddMonths(2),
                    signingCredentials: credentials);

                return new JwtSecurityTokenHandler()
                    .WriteToken(securityToken);
            };
        }

19 View Source File : AduDatePicker.cs
License : GNU General Public License v3.0
Project Creator : aduskin

private void PART_Btn_RecentlyAMonth_Click(object sender, RoutedEventArgs e)
      {
         this.ClearSelectedDates();
         this.FastSetSelectedDates(DateTime.Today.AddMonths(-1), DateTime.Today);
      }

19 View Source File : SiteMapNodeBlogDataAdapter.cs
License : MIT License
Project Creator : Adoxio

private static IBlogDataAdapter CreateBlogDataAdapter(
			SiteMapNode node,
			Func<Guid, IBlogDataAdapter> createAuthorArchiveAdapter,
			Func<DateTime, DateTime, IBlogDataAdapter> createMonthArchiveAdapter,
			Func<string, IBlogDataAdapter> createTagArchiveAdapter,
			Func<IBlogDataAdapter> createDefaultAdapter)
		{
			Guid authorId;

			if (BlogSiteMapProvider.TryGetAuthorArchiveNodeAttribute(node, out authorId))
			{
				return createAuthorArchiveAdapter(authorId);
			}

			DateTime monthArchiveDate;

			if (BlogSiteMapProvider.TryGetMonthArchiveNodeAttribute(node, out monthArchiveDate))
			{
				return createMonthArchiveAdapter(monthArchiveDate.Date, monthArchiveDate.Date.AddMonths(1));
			}

			string tag;

			if (BlogSiteMapProvider.TryGetTagArchiveNodeAttribute(node, out tag))
			{
				return createTagArchiveAdapter(tag);
			}

			return createDefaultAdapter();
		}

19 View Source File : JwtTokenExtensionMethods.cs
License : MIT License
Project Creator : angelsix

public static string GenerateJwtToken(this ApplicationUser user)
        {
            // Set our tokens claims
            var claims = new[]
            {
                // Unique ID for this token
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),

                // The username using the Idenreplacedy name so it fills out the HttpContext.User.Idenreplacedy.Name value
                new Claim(ClaimsIdenreplacedy.DefaultNameClaimType, user.UserName),

                // Add user Id so that UserManager.GetUserAsync can find the user based on Id
                new Claim(ClaimTypes.NameIdentifier, user.Id)
            };

            // Create the credentials used to generate the token
            var credentials = new SigningCredentials(
                // Get the secret key from configuration
                new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"])),
                // Use HS256 algorithm
                SecurityAlgorithms.HmacSha256);

            // Generate the Jwt Token
            var token = new JwtSecurityToken(
                issuer: Configuration["Jwt:Issuer"],
                audience: Configuration["Jwt:Audience"],
                claims: claims,
                signingCredentials: credentials,
                // Expire if not used for 3 months
                expires: DateTime.Now.AddMonths(3)
                );

            // Return the generated token
            return new JwtSecurityTokenHandler().WriteToken(token);
        }

19 View Source File : SalesDataGenerator.cs
License : MIT License
Project Creator : Actipro

protected override ICollection<SalesData> Generate() {
			// Create the results
			List<SalesData> results = new List<SalesData>();

			if (this.Options != null) {
				// Initialize the date
				DateTime date = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).AddMonths(-this.Options.Count);

				// Initialize the results with the first data item
				results.Add(new SalesData(date, this.Options.StartAmount));
				date.AddMonths(1);

				decimal delta = Convert.ToDecimal(this.Options.TrendPercentage) * this.Options.StepRange;
				for (int index = 1; index < this.Options.Count; index++) {
					decimal step = Convert.ToDecimal(this.Random.NextDouble()) * this.Options.StepRange;
					decimal amount = results[index - 1].Amount + step - delta;

					if (!this.AllowNegativeNumbers)
						amount = Math.Max(0, amount);

					results.Add(new SalesData(date, amount));
					date = date.AddMonths(1);
				}
			}

			return results;
		}

19 View Source File : Days360.cs
License : Apache License 2.0
Project Creator : Appdynamics

private int GetNumWholeMonths(System.DateTime dt1, System.DateTime dt2)
        {
            var startDate = new System.DateTime(dt1.Year, dt1.Month, 1).AddMonths(1);
            var endDate = new System.DateTime(dt2.Year, dt2.Month, 1);
            return ((endDate.Year - startDate.Year)*12) + (endDate.Month - startDate.Month);
        }

19 View Source File : IntegerDataGenerator.cs
License : MIT License
Project Creator : Actipro

protected override ICollection<IntegerData> Generate() {
			// Create the results
			List<IntegerData> results = new List<IntegerData>();

			if (this.Options != null) {
				// Initialize the date
				DateTime date = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).AddMonths(-this.Options.Count);

				// Initialize the results with the first data item
				results.Add(new IntegerData(date, this.Options.StartValue));
				date.AddMonths(1);

				double delta = this.Options.TrendPercentage * this.Options.StepRange;
				for (int index = 1; index < this.Options.Count; index++) {
					double step = this.Random.NextDouble() * this.Options.StepRange;
					int count = (int)Math.Round(results[index - 1].Value + step - delta);

					if (!this.AllowNegativeNumbers)
						count = Math.Max(0, count);

					results.Add(new IntegerData(date, count));
					date = date.AddMonths(1);
				}
			}

			return results;
		}

19 View Source File : DateAddOrSubtract.cs
License : MIT License
Project Creator : akaskela

protected override void Execute(CodeActivityContext context)
        {
            bool dateSet = false;
            if (this.Units != null && this.Number != null && this.Number.Get<int>(context) != 0)
            {
                OptionSetValue value = this.Units.Get<OptionSetValue>(context);
                if (value != null)
                {
                    switch (value.Value)
                    {
                        case 222540000:
                            ModifiedDate.Set(context, this.DateToModify.Get(context).AddYears(this.Number.Get<int>(context)));
                            break;
                        case 222540001:
                            ModifiedDate.Set(context, this.DateToModify.Get(context).AddMonths(this.Number.Get<int>(context)));
                            break;
                        case 222540002:
                            ModifiedDate.Set(context, this.DateToModify.Get(context).AddDays(this.Number.Get<int>(context) * 7));
                            break;
                        case 222540003:
                            ModifiedDate.Set(context, this.DateToModify.Get(context).AddDays(this.Number.Get<int>(context)));
                            break;
                        case 222540004:
                            ModifiedDate.Set(context, this.DateToModify.Get(context).AddHours(this.Number.Get<int>(context)));
                            break;
                        default:
                            ModifiedDate.Set(context, this.DateToModify.Get(context).AddMinutes(this.Number.Get<int>(context)));
                            break;
                    }
                    dateSet = true;
                }
            }

            if (!dateSet)
            {
                ModifiedDate.Set(context, this.DateToModify.Get(context));
            }
        }

19 View Source File : CalendarController.cs
License : MIT License
Project Creator : ahmetozlu

public void MonthPrev()
    {
        _dateTime = _dateTime.AddMonths(-1);
        CreateCalendar();
    }

public static double GetZSpread(IList<IList<double>> GridValues, int start, int end)
        {
            gridValues = GridValues;
            var cashList = new List<TermCashflowYieldSet>();
            var c = new ConnectedInstruction();
            var rowN = c.GetNumberOfRows();
            Console.WriteLine("Preparing Structured Load..." + DateTime.Now);
            for (int i = start; i < end; i++)
            {
                var spotYield = new SpotYield(Convert.ToDecimal(gridValues[i][1]), Enums.Term.MonthlyEffective);
                var termCashSet = new TermCashflowYieldSet(Convert.ToDecimal(gridValues[i][0]), 
                    (decimal)i, new DateTime(2002,1,1,1,1,1).AddMonths(i), spotYield);
                cashList.Add(termCashSet);
               // Console.WriteLine(i.ToString());
            }
            Console.WriteLine("Structured Load Complete..." + DateTime.Now);
            var cashflowSet = new ListTermCashflowSet(cashList, Enums.Term.MonthlyEffective);
            var spread = new ZSpread(cashflowSet, 10000m);
            Console.WriteLine("Success!..." + spread.ToString());
            return (double) spread.CalculateZspread();
        }

19 View Source File : EditSnapshotRuleForm.Schedule.cs
License : MIT License
Project Creator : alexis-

private void InitBaseSchedule()
    {
      DayCheckboxes = new[] { cbFreqWeeklySunday, cbFreqWeeklyMonday, cbFreqWeeklyTuesday, cbFreqWeeklyWednesday, cbFreqWeeklyThursday, cbFreqWeeklyFriday, cbFreqWeeklySaturday };

      ChangeDailyFreq(DailyFreq.Once);
      ChangeFreq(Freq.Daily);
      ChangeFreqWeekly(FreqWeekly.Weekly);

      cbDailyFreqEveryExcluding.Checked = false;
      ChangeDailyFreqEveryExcludingEnabled(false);

      llbFreqCronHelp.Links.Add(0, 0, "https://www.quartz-scheduler.net/doreplacedentation/quartz-3.x/tutorial/crontriggers.html");
      llbFreqCronGen.Links.Add(0, 0, "https://www.freeformatter.com/cron-expression-generator-quartz.html");

      dtpPeriodStart.Value = DateTime.Today;
      dtpPeriodEnd.Value = DateTime.Today.AddMonths(1);

      cbDailyFreqEvery.SelectedIndex = 1;

      for (int i = 0; i < cblFreqMonthlyMonths.Items.Count; i++)
        cblFreqMonthlyMonths.SereplacedemChecked(i, true);

      cblFreqMonthlyDays.SereplacedemChecked(0, true);

      cbFreqCronExcluding.Checked = false;
      ChangeCronExcludingEnabled(false);
    }

19 View Source File : FanChartExampleView.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private IEnumerable<VarPoint> GetVarianceData()
        {
            var dates = Enumerable.Range(0, 10).Select(i => new DateTime(2011, 01, 01).AddMonths(i)).ToArray();
            var yValues = new RandomWalkGenerator(seed: 0).GetRandomWalkSeries(10).YData;

            for (int i = 0; i < 10; i++)
            {
                double varMax = double.NaN;
                double var4 = double.NaN;
                double var3 = double.NaN;
                double var2 = double.NaN;
                double var1 = double.NaN;
                double varMin = double.NaN;

                if (i > 4)
                {
                    varMax = yValues[i] + (i - 5) * 0.3;
                    var4 = yValues[i] + (i - 5) * 0.2;
                    var3 = yValues[i] + (i - 5) * 0.1;
                    var2 = yValues[i] - (i - 5) * 0.1;
                    var1 = yValues[i] - (i - 5) * 0.2;
                    varMin = yValues[i] - (i - 5) * 0.3;
                }

                yield return new VarPoint(dates[i], yValues[i], var4, var3, var2, var1, varMin, varMax);
            }
        }

19 View Source File : DateExtensionsTests.cs
License : Apache License 2.0
Project Creator : AndcultureCode

[Fact]
        public void CalculateAge_Returns_Correct_Age_If_Birthday_Has_Happened_This_Year()
        {
            // Arrange
            var birthdate = DateTime.Today.AddMonths(1);
            birthdate = birthdate.AddYears(-5);

            // Act
            var result = birthdate.CalculateAge();

            // replacedert
            result.ShouldBe(4);
        }

19 View Source File : IdeaForumDataAdapterFactory.cs
License : MIT License
Project Creator : Adoxio

public IIdeaForumDataAdapter CreateIdeaForumDataAdapter(Enreplacedy ideaForum, string filter, string timeSpan, int? status = 1)
		{
			IIdeaForumDataAdapter ideaForumDataAdapter = null;

			if (string.Equals(filter, "new", StringComparison.InvariantCultureIgnoreCase))
			{
				ideaForumDataAdapter = new IdeaForumByNewDataAdapter(ideaForum);
			}
			else
			{
				ideaForumDataAdapter = this.IsIdeasPreRollup()
					? this.CreateIdeaDataAdapterPreRollup(ideaForum, filter)
					: this.CreateIdeaDataAdapter(ideaForum, filter);
			}

			ideaForumDataAdapter.MinDate = timeSpan == "this-year" ? DateTime.UtcNow.AddYears(-1).Date
				: timeSpan == "this-month" ? DateTime.UtcNow.AddMonths(-1).Date
				: timeSpan == "this-week" ? DateTime.UtcNow.AddDays(-7).Date
				: timeSpan == "today" ? DateTime.UtcNow.AddHours(-24)
				: (DateTime?)null;

			ideaForumDataAdapter.Status = status != (int?)IdeaStatus.Any ? status : null;

			return ideaForumDataAdapter;
		}

19 View Source File : ChartElement.cs
License : MIT License
Project Creator : AngeloCresta

internal static double GetIntervalSize(
			double current, 
			double interval, 
			DateTimeIntervalType type, 
			Series series,
			double intervalOffset, 
			DateTimeIntervalType intervalOffsetType,
			bool forceIntIndex,
			bool forceAbsInterval)
		{
			// AxisName is not date.
			if( type == DateTimeIntervalType.Number || type == DateTimeIntervalType.Auto )
			{
				return interval;
			}

			// Special case for indexed series
			if(series != null && series.IsXValueIndexed)
			{
				// Check point index
				int pointIndex = (int)Math.Ceiling(current - 1);
				if(pointIndex < 0)
				{
					pointIndex = 0;
				}
				if(pointIndex >= series.Points.Count || series.Points.Count <= 1)
				{
					return interval;
				}

				// Get starting and ending values of the closest interval
				double		adjuster = 0;
				double		xValue = series.Points[pointIndex].XValue;
				xValue = AlignIntervalStart(xValue, 1, type, null);
				double		xEndValue = xValue + GetIntervalSize(xValue, interval, type);
				xEndValue += GetIntervalSize(xEndValue, intervalOffset, intervalOffsetType);
				xValue += GetIntervalSize(xValue, intervalOffset, intervalOffsetType);
				if(intervalOffset < 0)
				{
					xValue = xValue + GetIntervalSize(xValue, interval, type);
					xEndValue = xEndValue + GetIntervalSize(xEndValue, interval, type);
				}

				// The first point in the series
				if(pointIndex == 0 && current < 0)
				{
					// Round the first point value depending on the interval type
					DateTime	dateValue = DateTime.FromOADate(series.Points[pointIndex].XValue);
					DateTime	roundedDateValue = dateValue;
					switch(type)
					{
						case(DateTimeIntervalType.Years): // Ignore hours,...
							roundedDateValue = new DateTime(dateValue.Year, 
								dateValue.Month, dateValue.Day, 0, 0, 0);
							break;

						case(DateTimeIntervalType.Months): // Ignore hours,...
							roundedDateValue = new DateTime(dateValue.Year, 
								dateValue.Month, dateValue.Day, 0, 0, 0);
							break;

						case(DateTimeIntervalType.Days): // Ignore hours,...
							roundedDateValue = new DateTime(dateValue.Year, 
								dateValue.Month, dateValue.Day, 0, 0, 0);
							break;

						case(DateTimeIntervalType.Hours): //
							roundedDateValue = new DateTime(dateValue.Year, 
								dateValue.Month, dateValue.Day, dateValue.Hour, 
								dateValue.Minute, 0);
							break;

						case(DateTimeIntervalType.Minutes):
							roundedDateValue = new DateTime(dateValue.Year, 
								dateValue.Month, 
								dateValue.Day, 
								dateValue.Hour, 
								dateValue.Minute, 
								dateValue.Second);
							break;

						case(DateTimeIntervalType.Seconds):
							roundedDateValue = new DateTime(dateValue.Year, 
								dateValue.Month, 
								dateValue.Day, 
								dateValue.Hour, 
								dateValue.Minute, 
								dateValue.Second,
								0);
							break;

						case(DateTimeIntervalType.Weeks):
							roundedDateValue = new DateTime(dateValue.Year, 
								dateValue.Month, dateValue.Day, 0, 0, 0);
							break;
					}

					// The first point value is exactly on the interval boundaries
					if(roundedDateValue.ToOADate() == xValue || roundedDateValue.ToOADate() == xEndValue)
					{
						return - current + 1;
					}
				}

				// Adjuster of 0.5 means that position should be between points
				++pointIndex;
				while(pointIndex < series.Points.Count)
				{
					if(series.Points[pointIndex].XValue >= xEndValue)
					{
						if(series.Points[pointIndex].XValue > xEndValue && !forceIntIndex)
						{
							adjuster = -0.5;
						}
						break;
					}

					++pointIndex;
				}

				// If last point outside of the max series index
				if(pointIndex == series.Points.Count)
				{
					pointIndex += series.Points.Count/5 + 1;
				}

				double size = (pointIndex + 1) - current + adjuster;
		
				return (size != 0) ? size : interval;
			}
	
			// Non indexed series
			else
			{
				DateTime	date = DateTime.FromOADate(current);
				TimeSpan	span = new TimeSpan(0);

				if(type == DateTimeIntervalType.Days)
				{
					span = TimeSpan.FromDays(interval);
				}
				else if(type == DateTimeIntervalType.Hours)
				{
					span = TimeSpan.FromHours(interval);
				}
				else if(type == DateTimeIntervalType.Milliseconds)
				{
					span = TimeSpan.FromMilliseconds(interval);
				}
				else if(type == DateTimeIntervalType.Seconds)
				{
					span = TimeSpan.FromSeconds(interval);
				}
				else if(type == DateTimeIntervalType.Minutes)
				{
					span = TimeSpan.FromMinutes(interval);
				}
				else if(type == DateTimeIntervalType.Weeks)
				{
					span = TimeSpan.FromDays(7.0 * interval);
				}
				else if(type == DateTimeIntervalType.Months)
				{
					// Special case handling when current date points 
					// to the last day of the month
					bool lastMonthDay = false;
					if(date.Day == DateTime.DaysInMonth(date.Year, date.Month))
					{
						lastMonthDay = true;
					}

					// Add specified amount of months
					date = date.AddMonths((int)Math.Floor(interval));
					span = TimeSpan.FromDays(30.0 * ( interval - Math.Floor(interval) ));

					// Check if last month of the day was used
					if(lastMonthDay && span.Ticks == 0)
					{
						// Make sure the last day of the month is selected
						int daysInMobth = DateTime.DaysInMonth(date.Year, date.Month);
						date = date.AddDays(daysInMobth - date.Day);
					}
				}
				else if(type == DateTimeIntervalType.Years)
				{
					date = date.AddYears((int)Math.Floor(interval));
					span = TimeSpan.FromDays(365.0 * ( interval - Math.Floor(interval) ));
				}

				// Check if an absolute interval size must be returned
				double result = date.Add(span).ToOADate() - current;
				if(forceAbsInterval)
				{
					result = Math.Abs(result);
				}
				return result;
			}
		}

19 View Source File : Index.cshtml.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task<IActionResult> OnPostClearLogAsync(int type)
        {
            switch (type)
            {
                case 1:

                    await _logAppService.ClearLog(DateTime.Now.AddYears(-1));
                    break;

                case 2:
                    await _logAppService.ClearLog(DateTime.Now.AddMonths(-6));
                    break;

                case 3:
                    await _logAppService.ClearLog(DateTime.Now.AddMonths(-3));
                    break;

                case 4:
                    await _logAppService.ClearLog(DateTime.Now.AddMonths(-1));
                    break;
            }




            return RedirectToPage("OperatorLog");
        }

19 View Source File : Date.cs
License : Apache License 2.0
Project Creator : Appdynamics

public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
        {
            ValidateArguments(arguments, 3);
            var year = ArgToInt(arguments, 0);
            var month = ArgToInt(arguments, 1);
            var day = ArgToInt(arguments, 2);
            var date = new System.DateTime(year, 1, 1);
            month -= 1;
            date = date.AddMonths(month);
            date = date.AddDays((double)(day - 1));
            return CreateResult(date.ToOADate(), DataType.Date);
        }

19 View Source File : MapController.cs
License : MIT License
Project Creator : Adoxio

public static IQueryable<Enreplacedy> FilterAlertsByDate(this IQueryable<Enreplacedy> query, int dateFilterCode, DateTime dateFrom, DateTime dateTo)
		{
			switch (dateFilterCode)
			{
				case 0: // filter last 7 days
					return query.Where(a => a.GetAttributeValue<DateTime?>("adx_scheduledstartdate").GetValueOrDefault() > DateTime.Now.AddDays(-7));
				case 1: // filter last 30 days
					return query.Where(a => a.GetAttributeValue<DateTime?>("adx_scheduledstartdate").GetValueOrDefault() > DateTime.Now.AddDays(-30));
				case 2: // filter last 12 months
					return query.Where(a => a.GetAttributeValue<DateTime?>("adx_scheduledstartdate").GetValueOrDefault() > DateTime.Now.AddMonths(-12));
				case 3: // filter by date range
					return query.Where(a => a.GetAttributeValue<DateTime?>("adx_scheduledstartdate").GetValueOrDefault() >= dateFrom && a.GetAttributeValue<DateTime?>("adx_scheduledstartdate").GetValueOrDefault() <= dateTo);
				default:
					return query;
			}
		}

19 View Source File : MapController.cs
License : MIT License
Project Creator : Adoxio

public static IQueryable<Enreplacedy> FilterServiceRequestsByDate(this IQueryable<Enreplacedy> query, int dateFilterCode, DateTime dateFrom, DateTime dateTo)
		{
			switch (dateFilterCode)
			{
				case 0: // filter last 7 days
					return query.Where(s => s.GetAttributeValue<DateTime?>("adx_incidentdate").GetValueOrDefault() > DateTime.Now.AddDays(-7));
				case 1: // filter last 30 days
					return query.Where(s => s.GetAttributeValue<DateTime?>("adx_incidentdate").GetValueOrDefault() > DateTime.Now.AddDays(-30));
				case 2: // filter last 12 months
					return query.Where(s => s.GetAttributeValue<DateTime?>("adx_incidentdate").GetValueOrDefault() > DateTime.Now.AddMonths(-12));
				case 3: // filter by date range
					return query.Where(s => s.GetAttributeValue<DateTime?>("adx_incidentdate").GetValueOrDefault() >= dateFrom && s.GetAttributeValue<DateTime?>("adx_incidentdate").GetValueOrDefault() <= dateTo);
				default:
					return query;
			}
		}

19 View Source File : WexTest.cs
License : MIT License
Project Creator : aabiryukov

public static void Test()
		{
/*
			{
				var apiClient = new WexApi(ApiKey, ApiSecret);
				var info = apiClient.GetInfo();
				Console.WriteLine("Info: BTC={0}, USD={1}", info.Funds.Btc, info.Funds.Usd);
				var order = apiClient.Trade(BtcePair.btc_usd, TradeType.Sell, 1245.8M, 3M);
				// 4.801251M
				Console.WriteLine("Order: {0}", order);
			}
*/

/*
			{
				var apiClient = new WexApi(ApiKey, ApiSecret);

				while (true)
				{
					var time = DateTime.Now;
					var userInfo = apiClient.GetInfo();
					var ping = Math.Round((DateTime.Now - time).TotalSeconds, 2);
					Console.WriteLine("Ping [{1}]: {0}", ping, userInfo.Funds.Btc);

					Thread.Sleep(1000);
				}
			}
*/
			{
				var ticker = WexApi.GetTicker(WexPair.btc_usd);
				Console.WriteLine(ticker);

				var depth3 = WexApiV3.GetDepth(new WexPair[] {WexPair.btc_usd});
				Console.WriteLine(depth3);

				var ticker3 = WexApiV3.GetTicker(new WexPair[] {WexPair.btc_usd});
				var trades3 = WexApiV3.GetTrades(new WexPair[] {WexPair.btc_usd});
				var trades = WexApi.GetTrades(WexPair.btc_usd);
				var btcusdDepth = WexApi.GetDepth(WexPair.usd_rur);
				var fee = WexApi.GetFee(WexPair.usd_rur);

				var apiClient = new WexApi(ApiKey, ApiSecret);
				var info = apiClient.GetInfo();
				Console.WriteLine("Info: BTC={0}, USD={1}", info.Funds.Btc, info.Funds.Usd);
				var transHistory = apiClient.GetTransHistory(since: DateTime.Now.AddMonths(-6));
				Console.WriteLine("transHistory count={0}", transHistory.Count);
				var tradeHistory = apiClient.GetTradeHistory(count: 20);
				Console.WriteLine(tradeHistory);
				var orderList = apiClient.ActiveOrders();
				Console.WriteLine("OrderList:");
				foreach (var or in orderList)
				{
					Console.WriteLine("{0}: {1}", or.Key, or.Value);
				}

//			var tradeAnswer = apiClient.Trade(BtcePair.btc_usd, TradeType.Sell, 20, 0.1m);
//			var cancelAnswer = apiClient.CancelOrder(tradeAnswer.OrderId);
			}
		}

19 View Source File : AduDatePicker.cs
License : GNU General Public License v3.0
Project Creator : aduskin

private void PART_Btn_RecentlyThreeMonth_Click(object sender, RoutedEventArgs e)
      {
         this.ClearSelectedDates();
         this.FastSetSelectedDates(DateTime.Today.AddMonths(-3), DateTime.Today);
      }

19 View Source File : IntegerDataGenerator.cs
License : MIT License
Project Creator : Actipro

protected override ICollection<IntegerData> Generate() {
			// Create the results
			List<IntegerData> results = new List<IntegerData>();

			if (this.Options != null) {
				// Initialize the date
				DateTime date = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).AddMonths(-this.Options.Count);

				// Initialize the results with the first data item
				results.Add(new IntegerData(date, this.Options.StartValue));
				date.AddMonths(1);

				double delta = this.Options.TrendPercentage * this.Options.StepRange;
				for (int index = 1; index < this.Options.Count; index++) {
					double step = this.Random.NextDouble() * this.Options.StepRange;
					int count = (int)Math.Round(results[index - 1].Value + step - delta);

					if (!this.AllowNegativeNumbers)
						count = Math.Max(0, count);

					results.Add(new IntegerData(date, count));
					date = date.AddMonths(1);
				}
			}

			return results;
		}

19 View Source File : AuditGetRecentUpdates.cs
License : MIT License
Project Creator : akaskela

protected DataTable BuildDataTable(CodeActivityContext context, IWorkflowContext workflowContext, IOrganizationService service)
        {
            TimeZoneSummary timeZone = StaticMethods.CalculateTimeZoneToUse(this.TimeZoneOption.Get(context), workflowContext, service);
            
            DataTable table = new DataTable() { TableName = workflowContext.PrimaryEnreplacedyName };
            table.Columns.AddRange(new DataColumn[] { new DataColumn("Date"), new DataColumn("User"), new DataColumn("Attribute"), new DataColumn("Old Value"), new DataColumn("New Value") });
            DateTime oldestUpdate = DateTime.MinValue;

            if (this.Units != null && this.Number != null && this.Number.Get<int>(context) != 0)
            {
                OptionSetValue value = this.Units.Get<OptionSetValue>(context);
                if (value != null)
                {
                    switch (value.Value)
                    {
                        case 222540000:
                            oldestUpdate = DateTime.Now.AddYears(this.Number.Get<int>(context) * -1);
                            break;
                        case 222540001:
                            oldestUpdate = DateTime.Now.AddMonths(this.Number.Get<int>(context) * -1);
                            break;
                        case 222540002:
                            oldestUpdate = DateTime.Now.AddDays(this.Number.Get<int>(context) * -7);
                            break;
                        case 222540003:
                            oldestUpdate = DateTime.Now.AddDays(this.Number.Get<int>(context) * -1);
                            break;
                        case 222540004:
                            oldestUpdate = DateTime.Now.AddHours(this.Number.Get<int>(context) * -1);
                            break;
                        default:
                            oldestUpdate = DateTime.Now.AddMinutes(this.Number.Get<int>(context) * -1);
                            break;
                    }
                }
            }

            int maxUpdates = this.MaxAuditLogs.Get(context) > 100 || this.MaxAuditLogs.Get(context) < 1 ? 100 : this.MaxAuditLogs.Get(context);
            RetrieveRecordChangeHistoryRequest request = new RetrieveRecordChangeHistoryRequest()
            {
                Target = new EnreplacedyReference(workflowContext.PrimaryEnreplacedyName, workflowContext.PrimaryEnreplacedyId),
                PagingInfo = new PagingInfo() { Count = maxUpdates, PageNumber = 1 }
            };
            RetrieveRecordChangeHistoryResponse response = service.Execute(request) as RetrieveRecordChangeHistoryResponse;
            var detailsToInclude = response.AuditDetailCollection.AuditDetails
                .Where(ad => ad is AttributeAuditDetail && ad.AuditRecord.Contains("createdon") && ((DateTime)ad.AuditRecord["createdon"]) > oldestUpdate)
                .OrderByDescending(ad => ((DateTime)ad.AuditRecord["createdon"]))
                .ToList();

            if (detailsToInclude.Any())
            {
                Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyRequest retrieveEnreplacedyRequest = new Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyRequest()
                {
                    EnreplacedyFilters = EnreplacedyFilters.Attributes,
                    LogicalName = workflowContext.PrimaryEnreplacedyName
                };
                Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyResponse retrieveEnreplacedyResponse = service.Execute(retrieveEnreplacedyRequest) as Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyResponse;
                EnreplacedyMetadata metadata = retrieveEnreplacedyResponse.EnreplacedyMetadata;

                foreach (var detail in detailsToInclude.Select(d => d as AttributeAuditDetail).Where(d => d.NewValue != null && d.OldValue != null))
                {
                    DateTime dateToModify = (DateTime)detail.AuditRecord["createdon"];
                    if (dateToModify.Kind != DateTimeKind.Utc)
                    {
                        dateToModify = dateToModify.ToUniversalTime();
                    }


                    LocalTimeFromUtcTimeRequest timeZoneChangeRequest = new LocalTimeFromUtcTimeRequest() { UtcTime = dateToModify, TimeZoneCode = timeZone.MicrosoftIndex };
                    LocalTimeFromUtcTimeResponse timeZoneResponse = service.Execute(timeZoneChangeRequest) as LocalTimeFromUtcTimeResponse;
                    DateTime timeZoneSpecificDateTime = timeZoneResponse.LocalTime;

                    var details = detail.NewValue.Attributes.Keys.Union(detail.OldValue.Attributes.Keys)
                        .Distinct()
                        .Select(a =>
                        new {
                            AttributeName = a,
                            DisplayName = GetDisplayLabel(metadata, a)
                        })
                        .OrderBy(a => a.DisplayName);

                    foreach (var item in details)
                    {
                        DataRow newRow = table.NewRow();
                        newRow["User"] = GetDisplayValue(detail.AuditRecord, "userid");
                        newRow["Date"] = timeZoneSpecificDateTime.ToString("MM/dd/yyyy h:mm tt");
                        newRow["Attribute"] = item.DisplayName;
                        newRow["Old Value"] = GetDisplayValue(detail.OldValue, item.AttributeName);
                        newRow["New Value"] = GetDisplayValue(detail.NewValue, item.AttributeName);
                        table.Rows.Add(newRow);
                    }
                }
            }
            return table;
        }

19 View Source File : CalendarController.cs
License : MIT License
Project Creator : ahmetozlu

public void MonthNext()
    {
        _dateTime = _dateTime.AddMonths(1);
        CreateCalendar();
    }

19 View Source File : BankIdSimulatedApiClient.cs
License : MIT License
Project Creator : ActiveLogin

private CompletionData? GetCompletionData(string endUserIp, CollectStatus status, string personalIdenreplacedyNumber)
        {
            if (status != CollectStatus.Complete)
            {
                return null;
            }

            var user = new User(personalIdenreplacedyNumber, _name, _givenName, _surname);
            var device = new Device(endUserIp);

            var certNow = DateTime.UtcNow;
            var certNotBefore = UnixTimestampMillisecondsFromDateTime(certNow.AddMonths(-1));
            var certNotAfter = UnixTimestampMillisecondsFromDateTime(certNow.AddMonths(1));
            var cert = new Cert(certNotBefore.ToString("D"), certNotAfter.ToString("D"));

            var signature = string.Empty; // Not implemented in the simulated client
            var ocspResponse = string.Empty; // Not implemented in the simulated client

            return new CompletionData(user, device, cert, signature, ocspResponse);
        }

19 View Source File : UpdateChecker.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

private static void NextUpdateCallback(Popup p)
        {
            if (p.IndexOfGivenAnswer == 0)
            {
                Game.LogTrivial("Continue pressed");
                Index++;
                if (PluginsDownloadLink.Count > Index)
                {
                    Popup pop = new Popup("Albo1125.Common Update Check", "Update " + (Index + 1) + ": " + PluginsDownloadLink[Index].Item1, new List<string>() { "Continue", "Go to download page" },
                        false, false, NextUpdateCallback);
                    pop.Display();
                }
                else
                {
                    Popup pop = new Popup("Albo1125.Common Update Check", "Please install updates to maintain stability and don't request support for old versions.",
                        new List<string>() { "-", "Open installation/troubleshooting video tutorial", "Continue to game.", "Delay next update check by a week.", "Delay next update check by a month.",
                            "Fully disable update checks (not recommended)." }, false, false, NextUpdateCallback);
                    pop.Display();
                }
            }
            else if (p.IndexOfGivenAnswer == 1)
            {
                Game.LogTrivial("GoToDownload pressed.");
                if (PluginsDownloadLink.Count > Index && Index >= 0)
                {
                    System.Diagnostics.Process.Start(PluginsDownloadLink[Index].Item2);
                }
                else
                {
                    System.Diagnostics.Process.Start("https://youtu.be/af434m72rIo?list=PLEKypmos74W8PMP4k6xmVxpTKdebvJpFb");
                }
                p.Display();
            }
            else if (p.IndexOfGivenAnswer == 2)
            {
                Game.LogTrivial("ExitButton pressed.");
            }
            else if (p.IndexOfGivenAnswer == 3)
            {
                Game.LogTrivial("Delay by week pressed");
                DateTime NextUpdateCheckDT = DateTime.Now.AddDays(6);
                XDoreplacedent CommonVariablesDoc = XDoreplacedent.Load("Albo1125.Common/CommonVariables.xml");
                if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
                CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value = NextUpdateCheckDT.ToBinary().ToString();
                CommonVariablesDoc.Save("Albo1125.Common/CommonVariables.xml");
                CommonVariablesDoc = null;
            }
            else if (p.IndexOfGivenAnswer == 4)
            {
                Game.LogTrivial("Delay by month pressed");
                DateTime NextUpdateCheckDT = DateTime.Now.AddMonths(1);
                XDoreplacedent CommonVariablesDoc = XDoreplacedent.Load("Albo1125.Common/CommonVariables.xml");
                if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
                CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value = NextUpdateCheckDT.ToBinary().ToString();
                CommonVariablesDoc.Save("Albo1125.Common/CommonVariables.xml");
                CommonVariablesDoc = null;
            }
            else if (p.IndexOfGivenAnswer == 5)
            {
                Game.LogTrivial("Disable Update Checks pressed.");
                XDoreplacedent CommonVariablesDoc = XDoreplacedent.Load("Albo1125.Common/CommonVariables.xml");
                if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
                CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value = replacedembly.GetExecutingreplacedembly().GetName().Version.ToString();
                CommonVariablesDoc.Save("Albo1125.Common/CommonVariables.xml");
                CommonVariablesDoc = null;
                Popup pop = new Popup("Albo1125.Common Update Check", "Update checking has been disabled for this version of Albo1125.Common." +
                    "To re-enable it, delete the Albo1125.Common folder from your Grand Theft Auto V folder. Please do not request support for old versions.", false, true);
                pop.Display();
            }
        }

19 View Source File : TransactionStatsQueriesHandler.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<List<int>> Handle(TransactionStatsOverYearQuery request, CancellationToken cancellationToken)
        {
            // end Date 6/4/ 2020
            // start date 1/1/2019
            // the stats will
            // CurrentYear : 1/1/20, 1/2/20, 1/3/20, 1/4/20, 1/5/20 = 0, 1/6/20 = 0, 1/7/20 = 0, ...
            var startDate = DateTime.UtcNow.AddMonths(-DateTime.UtcNow.Month + 1).AddDays(-DateTime.UtcNow.Day + 1).Date;
            var endDate = DateTime.UtcNow.Date.AddDays(1);

            var transesMonthly = (from r in _receivingsRepo.Table
                                  where
                                     r.ReceivedAtUtc >= startDate && r.ReceivedAtUtc <= endDate
                                  group r by new
                                  {
                                      r.ReceivedAtUtc.Year,
                                      r.ReceivedAtUtc.Month
                                  } into g
                                  select new
                                  {
                                      Count = g.Count(),
                                      MonthYear = new DateTime(g.Key.Year, g.Key.Month, 1)
                                  }).ToList();

            var months = Enumerable.Range(0, 12).Select(offset => startDate.AddMonths(offset)).ToList();

            months.ForEach(month =>
            {
                if (!transesMonthly.Any(u => u.MonthYear.Year == month.Year && u.MonthYear.Month == month.Month))
                {
                    transesMonthly.Add(new
                    {
                        Count = 0,
                        MonthYear = month,
                    });
                }
            });

            return transesMonthly.Select(m => m.Count).ToList();
        }

19 View Source File : DateTimeAxis.cs
License : MIT License
Project Creator : AlexGyver

private IList<double> CreateDateTickValues(
            double min, double max, double step, DateTimeIntervalType intervalType)
        {
            DateTime start = ToDateTime(min);
            switch (intervalType)
            {
                case DateTimeIntervalType.Weeks:

                    // make sure the first tick is at the 1st day of a week
                    start = start.AddDays(-(int)start.DayOfWeek + (int)this.FirstDayOfWeek);
                    break;
                case DateTimeIntervalType.Months:

                    // make sure the first tick is at the 1st of a month
                    start = new DateTime(start.Year, start.Month, 1);
                    break;
                case DateTimeIntervalType.Years:

                    // make sure the first tick is at Jan 1st
                    start = new DateTime(start.Year, 1, 1);
                    break;
            }

            // Adds a tick to the end time to make sure the end DateTime is included.
            DateTime end = ToDateTime(max).AddTicks(1);

            DateTime current = start;
            var values = new Collection<double>();
            double eps = step * 1e-3;
            DateTime minDateTime = ToDateTime(min - eps);
            DateTime maxDateTime = ToDateTime(max + eps);
            while (current < end)
            {
                if (current > minDateTime && current < maxDateTime)
                {
                    values.Add(ToDouble(current));
                }

                switch (intervalType)
                {
                    case DateTimeIntervalType.Months:
                        current = current.AddMonths((int)Math.Ceiling(step));
                        break;
                    case DateTimeIntervalType.Years:
                        current = current.AddYears((int)Math.Ceiling(step));
                        break;
                    default:
                        current = current.AddDays(step);
                        break;
                }
            }

            return values;
        }

19 View Source File : DateTimePicker.xaml.cs
License : MIT License
Project Creator : ADeltaX

private DateTime Increase(int selstart, int value)
		{
			DateTime retval = (ParseDateText(false) ?? SelectedDate);

			try
			{
				switch (DateFormat.Substring(selstart, 1))
				{
					case "h":
					case "H":
						retval = retval.AddHours(value);
						break;
					case "y":
						retval = retval.AddYears(value);
						break;
					case "M":
						retval = retval.AddMonths(value);
						break;
					case "m":
						retval = retval.AddMinutes(value);
						break;
					case "d":
						retval = retval.AddDays(value);
						break;
					case "s":
						retval = retval.AddSeconds(value);
						break;
				}
			}
			catch (ArgumentException ex)
			{
				//Catch dates with year over 9999 etc, dont throw
			}

			return retval;
		}

19 View Source File : OandaClient.cs
License : Apache License 2.0
Project Creator : AlexWan

public async void ExecuteOrder(Order order)
        {
            if (_isConnected == false)
            {
                return;
            }

            _orders.Add(order);

            try
            {
                string expiry = ConvertDateTimeToAcceptDateFormat(DateTime.Now.AddMonths(1));

                decimal volume = order.Volume;

                if (order.Side == Side.Sell)
                {
                    volume = -order.Volume;
                }
                string price = order.Price.ToString(new CultureInfo("en-US"));

                Instrument myInstrument = _allInstruments.Find(inst => inst.name == order.SecurityNameCode);

                // create new pending order
                var request = new LimitOrderRequest(myInstrument)
                {
                    instrument = order.SecurityNameCode,
                    units = Convert.ToInt64(volume),
                    timeInForce = TimeInForce.GoodUntilDate,
                    gtdTime = expiry,
                    price = price.ToDecimal(),

                    clientExtensions = new ClientExtensions()
                    {
                        id = order.NumberUser.ToString(),
                        comment = "",
                        tag = ""
                    },
                    tradeClientExtensions = new ClientExtensions()
                    {
                        id = order.NumberUser.ToString(),
                        comment = "",
                        tag = ""
                    }
                };
                
                var response = await Rest20.PostOrderAsync(Credentials.GetDefaultCredentials().DefaultAccountId, request);
                var orderTransaction = response.orderCreateTransaction;

                if (orderTransaction.id > 0)
                {
                    order.NumberMarket = orderTransaction.id.ToString();
                }
            }
            catch (Exception error)
            {
                SendLogMessage(error.ToString(), LogMessageType.Error);
            }
        }

19 View Source File : Yun.cs
License : MIT License
Project Creator : 6tail

public Solar getStartSolar()
        {
            Solar birth = lunar.getSolar();
            DateTime c = ExactDate.fromYmd(birth.getYear(), birth.getMonth(), birth.getDay());
            c = c.AddYears(startYear);
            c = c.AddMonths(startMonth);
            c = c.AddDays(startDay);
            return Solar.fromDate(c);
        }

19 View Source File : ApplicationContextSeed.cs
License : MIT License
Project Creator : Amitpnk

private static List<Event> EventsList()
        {
            return new List<Event>()
            {
                new Event
                {
                    Id = Guid.NewGuid(),
                    Name = "Guitar hits 2020",
                    Date = DateTime.Now.AddMonths(4),
                    Description = "Guitar music concert 2020",
                    CategoryId = musicalGuid
                },

                new Event
                {
                    Id = Guid.NewGuid(),
                    Name = "Guitar hits 2021",
                    Date = DateTime.Now.AddMonths(4),
                    Description = "Guitar music concert 2021",
                    CategoryId = musicalGuid
                },

                new Event
                {
                    Id = Guid.NewGuid(),
                    Name = "Event 2020",
                    Date = DateTime.Now.AddMonths(10),
                    Description = "The tech conference in c#",
                    CategoryId = conferenceGuid
                },

                new Event
                {
                    Id = Guid.NewGuid(),
                    Name = "Event 2021",
                    Date = DateTime.Now.AddMonths(8),
                    Description = "The tech conference in .net core",
                    CategoryId = conferenceGuid
                },
            };
        }

19 View Source File : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio

public static IEnumerable<DateTime> GetDates(this OrganizationServiceContext context, Enreplacedy eventSchedule, DateTime firstDate, DateTime lastDate)
		{
			eventSchedule.replacedertEnreplacedyName("adx_eventschedule");

			var interval = eventSchedule.GetAttributeValue<int?>("adx_interval");
			var recurrenceOption = eventSchedule.GetAttributeValue<OptionSetValue>("adx_recurrence");
			var recurrence = recurrenceOption == null ? null : (int?)recurrenceOption.Value;
			var startTime = eventSchedule.GetAttributeValue<DateTime?>("adx_starttime");
			var endTime = eventSchedule.GetAttributeValue<DateTime?>("adx_endtime");
			var maxRecurrences = eventSchedule.GetAttributeValue<int?>("adx_maxrecurrences");
			var weekOption = eventSchedule.GetAttributeValue<OptionSetValue>("adx_week");
			var week = weekOption == null ? null : (int?)weekOption.Value;
			var recurrenceEndDate = eventSchedule.GetAttributeValue<DateTime?>("adx_recurrenceenddate");

			var scheduledDates = new List<DateTime>();
			var intervalValue = interval.HasValue ? interval.Value : 1;

			if (recurrence == 1 /*"Nonrecurring"*/)
			{
				// this is a nonrecurring event.  We only need to add the current date
				if (endTime >= firstDate && startTime < lastDate)
				{
					scheduledDates.Add(startTime.Value);
				}
			}
			else if (recurrence == 2 /*"Daily"*/)
			{
				DateTime d = startTime.Value;
				var done = false;
				var counter = 0;

				while (!done)
				{
					// check if the time for this event is between now and the maximum timespan
					if (d >= firstDate && d < lastDate)
					{
						var sunday = eventSchedule.GetAttributeValue<bool?>("adx_sunday");
						var monday = eventSchedule.GetAttributeValue<bool?>("adx_monday");
						var tuesday = eventSchedule.GetAttributeValue<bool?>("adx_tuesday");
						var wednesday = eventSchedule.GetAttributeValue<bool?>("adx_wednesday");
						var thursday = eventSchedule.GetAttributeValue<bool?>("adx_thursday");
						var friday = eventSchedule.GetAttributeValue<bool?>("adx_friday");
						var saturday = eventSchedule.GetAttributeValue<bool?>("adx_saturday");

						// this is in our date window.  Check if there are restrictions on the days
						if (
							(d.DayOfWeek == DayOfWeek.Sunday && (sunday != null && sunday.Value)) ||
							(d.DayOfWeek == DayOfWeek.Monday && (monday != null && monday.Value)) ||
							(d.DayOfWeek == DayOfWeek.Tuesday && (tuesday != null && tuesday.Value)) ||
							(d.DayOfWeek == DayOfWeek.Wednesday && (wednesday != null && wednesday.Value)) ||
							(d.DayOfWeek == DayOfWeek.Thursday && (thursday != null && thursday.Value)) ||
							(d.DayOfWeek == DayOfWeek.Friday && (friday != null && friday.Value)) ||
							(d.DayOfWeek == DayOfWeek.Saturday && (saturday != null && saturday.Value)))
						{
							scheduledDates.Add(d);
						}
					}

					// move to the next event
					d = d.AddDays(intervalValue);

					if ((maxRecurrences.HasValue ? counter++ >= maxRecurrences : false) || d > lastDate || d > recurrenceEndDate)
					{
						done = true;
					}
				}
			}
			else if (recurrence == 3 /*"Weekly"*/)
			{
				DateTime d = startTime.Value;
				var done = false;
				var counter = 0;

				while (!done)
				{
					// check if the time for this event is between now and the maximum timespan
					if (d >= firstDate && d < lastDate)
					{
						// this is in our date window. 
						scheduledDates.Add(d);
					}

					// move to the next event
					d = d.AddDays(intervalValue * 7);

					if ((maxRecurrences.HasValue ? counter++ >= maxRecurrences : false) || d > lastDate || d > recurrenceEndDate)
					{
						done = true;
					}
				}
			}
			else if (recurrence == 4 /*"Monthly"*/ && week == null)
			{
				DateTime d = startTime.Value;
				var done = false;
				var counter = 0;

				while (!done)
				{
					// check if the time for this event is between now and the maximum timespan
					if (d >= firstDate && d < lastDate)
					{
						// this is in our date window. 
						scheduledDates.Add(d);
					}

					// move to the next event
					d = d.AddMonths(intervalValue);

					if ((maxRecurrences.HasValue ? counter++ >= maxRecurrences : false) || d > lastDate || d > recurrenceEndDate)
					{
						done = true;
					}
				}
			}
			else if (recurrence == 4 /*"Monthly"*/ && week != null)
			{
				DateTime d = startTime.Value;
				var done = false;
				var counter = 0;

				while (!done)
				{
					var d2 = new DateTime(d.Year, d.Month, 1, d.Hour, d.Minute, d.Second);
					if (week == 2 /*"Second"*/)
					{
						d2 = d2.AddDays(7);
					}
					else if (week == 3 /*"Third"*/)
					{
						d2 = d2.AddDays(14);
					}
					else if (week == 4 /*"Fourth"*/)
					{
						d2 = d2.AddDays(21);
					}
					else if (week == 5 /*"Last"*/)
					{
						d2 = d2.AddMonths(1);
						d2 = d2.AddDays(-7);
					}

					// move forward to the first scheduled day that matches the original day
					while (d2.DayOfWeek != startTime.Value.DayOfWeek)
					{
						d2 = d2.AddDays(1);
					}

					// check if the time for this event is between now and the maximum timespan
					if (d2 >= firstDate && d2 < lastDate)
					{
						// this is in our date window. 
						scheduledDates.Add(d2);
					}

					// move to the next event
					d = d.AddMonths(intervalValue);

					// check if we are done, but be careful that we might have to check another iteration if the date is
					// a little past the specified date and the setting is set to use the 'last' week of the month. It is safe to 
					// check an extra week past our final date.
					if ((maxRecurrences.HasValue ? counter++ >= maxRecurrences : false) || d > lastDate.AddDays(7) || d > recurrenceEndDate)
					{
						done = true;
					}
				}
			}

			var eventScheduleExceptions = eventSchedule.GetRelatedEnreplacedies(context, "adx_eventschedule_eventscheduleexception");

			foreach (var scheduleException in eventScheduleExceptions)
			{
				var scheduledTime = scheduleException.GetAttributeValue<DateTime?>("adx_scheduledtime");

				// check if this scheduled date was in the list of dates we calculated, and remove it if it is
				if (scheduledDates.Contains(scheduledTime.Value))
				{
					scheduledDates.Remove(scheduledTime.Value);
				}

				var rebookingTime = scheduleException.GetAttributeValue<DateTime?>("adx_rebookingtime");

				// check if this rescheduled date fits within our time window
				if (rebookingTime.HasValue && rebookingTime.Value >= firstDate && rebookingTime.Value < lastDate)
				{
					scheduledDates.Add(rebookingTime.Value);
				}
			}

			return scheduledDates;
		}

19 View Source File : DateExtensionsTests.cs
License : Apache License 2.0
Project Creator : AndcultureCode

[Fact]
        public void CalculateAge_Returns_Correct_Age_If_Birthday_Has_Not_Happened_This_Year()
        {
            // Arrange
            var birthdate = DateTime.Today.AddMonths(-1);
            birthdate = birthdate.AddYears(-5);

            // Act
            var result = birthdate.CalculateAge();

            // replacedert
            result.ShouldBe(5);
        }

19 View Source File : BoxPlotExampleView.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private IEnumerable<BoxPoint> GetBoxPlotData(int count)
        {
            var dates = Enumerable.Range(0, count).Select(i => new DateTime(2011, 01, 01).AddMonths(i)).ToArray();
            var medianValues = new RandomWalkGenerator(0).GetRandomWalkSeries(count).YData;

            var random = new Random(0);
            for (int i = 0; i < count; i++)
            {
                double med = medianValues[i];

                double min = med - random.NextDouble();
                double max = med + random.NextDouble();

                double lower = (med - min)*random.NextDouble() + min;
                double upper = (max - med)*random.NextDouble() + med;

                yield return new BoxPoint(dates[i], min, lower, med, upper, max);
            }
        }

19 View Source File : ChartElement.cs
License : MIT License
Project Creator : AngeloCresta

internal static double AlignIntervalStart(double start, double intervalSize, DateTimeIntervalType type, Series series, bool majorInterval)
		{
			// Special case for indexed series
			if(series != null && series.IsXValueIndexed)
			{
				if(type == DateTimeIntervalType.Auto ||
					type == DateTimeIntervalType.Number)
				{
					if( majorInterval )
					{
						return 1;
					}
					else
					{
						return 0;
					}
				}
					
				return -(series.Points.Count + 1);
			}

			// Non indexed series
			else
			{
				// Do not adjust start position for these interval type
				if(type == DateTimeIntervalType.Auto ||
					type == DateTimeIntervalType.Number)
				{
					return start;
				}

				// Get the beginning of the interval depending on type
				DateTime	newStartDate = DateTime.FromOADate(start);

				// Adjust the months interval depending on size
				if(intervalSize > 0.0 && intervalSize != 1.0)
				{
					if(type == DateTimeIntervalType.Months && intervalSize <= 12.0 && intervalSize > 1)
					{
						// Make sure that the beginning is aligned correctly for cases
						// like quarters and half years
						DateTime	resultDate = newStartDate;
						DateTime	sizeAdjustedDate = new DateTime(newStartDate.Year, 1, 1, 0, 0, 0);
						while(sizeAdjustedDate < newStartDate)
						{
							resultDate = sizeAdjustedDate;
							sizeAdjustedDate = sizeAdjustedDate.AddMonths((int)intervalSize);
						}

						newStartDate = resultDate;
						return newStartDate.ToOADate();
					}
				}

				// Check interval type
				switch(type)
				{
					case(DateTimeIntervalType.Years):
						int year = (int)((int)(newStartDate.Year / intervalSize) * intervalSize);
						if(year <= 0)
						{
							year = 1;
						}
						newStartDate = new DateTime(year, 
							1, 1, 0, 0, 0);
						break;

					case(DateTimeIntervalType.Months):
						int month = (int)((int)(newStartDate.Month / intervalSize) * intervalSize);
						if(month <= 0)
						{
							month = 1;
						}
						newStartDate = new DateTime(newStartDate.Year, 
							month, 1, 0, 0, 0);
						break;

					case(DateTimeIntervalType.Days):
						int day = (int)((int)(newStartDate.Day / intervalSize) * intervalSize);
						if(day <= 0)
						{
							day = 1;
						}
						newStartDate = new DateTime(newStartDate.Year, 
							newStartDate.Month, day, 0, 0, 0);
						break;

					case(DateTimeIntervalType.Hours):
						int hour = (int)((int)(newStartDate.Hour / intervalSize) * intervalSize);
						newStartDate = new DateTime(newStartDate.Year, 
							newStartDate.Month, newStartDate.Day, hour, 0, 0);
						break;

					case(DateTimeIntervalType.Minutes):
						int minute = (int)((int)(newStartDate.Minute / intervalSize) * intervalSize);
						newStartDate = new DateTime(newStartDate.Year, 
							newStartDate.Month, 
							newStartDate.Day, 
							newStartDate.Hour, 
							minute, 
							0);
						break;

					case(DateTimeIntervalType.Seconds):
						int second = (int)((int)(newStartDate.Second / intervalSize) * intervalSize);
						newStartDate = new DateTime(newStartDate.Year, 
							newStartDate.Month, 
							newStartDate.Day, 
							newStartDate.Hour, 
							newStartDate.Minute, 
							second, 
							0);
						break;

					case(DateTimeIntervalType.Milliseconds):
						int milliseconds = (int)((int)(newStartDate.Millisecond / intervalSize) * intervalSize);
						newStartDate = new DateTime(newStartDate.Year, 
							newStartDate.Month, 
							newStartDate.Day, 
							newStartDate.Hour, 
							newStartDate.Minute, 
							newStartDate.Second, 
							milliseconds);
						break;

					case(DateTimeIntervalType.Weeks):

                        // NOTE: Code below was changed to fix issue #5962
                        // Elements that have interval set to weeks should be aligned to the 
                        // nearest Monday no matter how many weeks is the interval.
						//newStartDate = newStartDate.AddDays(-((int)newStartDate.DayOfWeek * intervalSize));
                        newStartDate = newStartDate.AddDays(-((int)newStartDate.DayOfWeek));
						newStartDate = new DateTime(newStartDate.Year, 
							newStartDate.Month, newStartDate.Day, 0, 0, 0);
						break;
				}

				return newStartDate.ToOADate();
			}
		}

19 View Source File : DateFilters.cs
License : MIT License
Project Creator : Adoxio

public static DateTime? DateAddMonths(DateTime? date, int value)
		{
			return date.HasValue
				? date.Value.AddMonths(value)
				: (DateTime?)null;
		}

19 View Source File : LocalData.cs
License : MIT License
Project Creator : AntonyCorbett

public HistoricalMeetingTimes? GetHistoricalTimingData(DateTime dt)
        {
            HistoricalMeetingTimes? result = null;

            var startDate = dt.AddMonths(-HistoricalMonths);
            var times = GetMeetingTimesRange(startDate, dt);

            foreach (var t in times)
            {
                if (t.MeetingPlannedEnd != default && t.MeetingActualEnd != default)
                {
                    result ??= new HistoricalMeetingTimes();

                    var summary = new MeetingTimeSummary
                    {
                        MeetingDate = t.MeetingDate,
                        Overtime = t.GetMeetingOvertime()
                    };

                    result.Add(summary);
                }
            }

            result?.Sort();

            return result;
        }

19 View Source File : SolarMonth.cs
License : MIT License
Project Creator : 6tail

public SolarMonth next(int months)
        {
            DateTime c = ExactDate.fromYmd(year, month, 1);
            c = c.AddMonths(months);
            return new SolarMonth(c);
        }

19 View Source File : DatetimeImplementation.cs
License : MIT License
Project Creator : apexsharp

public Datetime addMonths(int months) => new DatetimeInstance(dateTime.AddMonths(months));

19 View Source File : ConferenceEvent.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void Page_Load(object sender, EventArgs args)
		{
			var @event = _portal.Value.Enreplacedy;

			if (@event == null || @event.LogicalName != "adx_event")
			{
				return;
			}

			var dataAdapter = new EventDataAdapter(@event, new PortalContextDataAdapterDependencies(_portal.Value, PortalName));
			var now = DateTime.UtcNow;
			
			var occurrences = (PortalConference != null) ? dataAdapter.SelectEventOccurrences(PortalConference.GetAttributeValue<DateTime?>("adx_startingdate").GetValueOrDefault(now.AddMonths(-3)), PortalConference.GetAttributeValue<DateTime?>("adx_enddate").GetValueOrDefault(now.AddMonths(3))).ToArray() : 
				dataAdapter.SelectEventOccurrences(now.AddMonths(-3), now.AddMonths(3)).ToArray();

			IEventOccurrence requestOccurrence;

			RequestEventOccurrence = dataAdapter.TryMatchRequestEventOccurrence(Request, occurrences, out requestOccurrence)
				? requestOccurrence
				: occurrences.Length == 1 ? occurrences.Single() : null;

			var user = _portal.Value.User;

			CanRegister = Request.IsAuthenticated && user != null && RequestEventOccurrence != null && RequestEventOccurrence.Start >= now &&
				(@event.GetAttributeValue<EnreplacedyReference>("adx_conferenceid") != null && UserIsRegisteredForConference
				|| @event.GetAttributeValue<EnreplacedyReference>("adx_conferenceid") == null);

			RequiresRegistration = (@event.GetAttributeValue<bool?>("adx_requiresregistration").GetValueOrDefault()
				|| @event.GetAttributeValue<EnreplacedyReference>("adx_conferenceid") != null && UserIsRegisteredForConference)
				&& RequestEventOccurrence != null
				&& RequestEventOccurrence.Start >= now;

			if (CanRegister)
			{
				var registration = _portal.Value.ServiceContext.CreateQuery("adx_eventregistration")
					.FirstOrDefault(e => e.GetAttributeValue<EnreplacedyReference>("adx_attendeeid") == user.ToEnreplacedyReference()
						&& e.GetAttributeValue<EnreplacedyReference>("adx_eventscheduleid") == RequestEventOccurrence.EventSchedule.ToEnreplacedyReference());

				if (registration != null)
				{
					Unregister.CommandArgument = registration.Id.ToString();
					IsRegistered = true;
				}
			}

			OtherOccurrences.DataSource = occurrences
				.Where(e => e.Start >= now)
				.Where(e => RequestEventOccurrence == null || !(e.EventSchedule.Id == RequestEventOccurrence.EventSchedule.Id && e.Start == RequestEventOccurrence.Start));

			OtherOccurrences.DataBind();

			var sessionEvent = @event;

			Speakers.DataSource = sessionEvent.GetRelatedEnreplacedies(_portal.Value.ServiceContext, new Relationship("adx_eventspeaker_event"));
			Speakers.DataBind();
		}

19 View Source File : TimeAggregatedDataGenerator.cs
License : MIT License
Project Creator : Actipro

public void Generate() {
			// Create a random number generator
			var resolvedRandomSeed = randomSeed ?? Environment.TickCount;
			var random = new Random(resolvedRandomSeed);

			// Initialize the date
			DateTime date;
			var resolvedDataPointCount = this.DataPointCount;
			switch (timePeriod) {
				case TimePeriod.Month:
					date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
					date = date.AddMonths(-resolvedDataPointCount);
					break;
				case TimePeriod.Week:
					date = DateTime.Today;
					date = date.AddDays(-resolvedDataPointCount * 7);
					break;
				default:  // Year
					date = new DateTime(DateTime.Today.Year, 1, 1);
					date = date.AddYears(-resolvedDataPointCount);
					break;
			}

			// Initialize the results with the first data item
			this.BeginUpdate();
			try {
				this.Clear();

				// Quit if there are no data points
				if (resolvedDataPointCount == 0)
					return;
				
				// Determine the trend percentage
				double trendPercentage;
				switch (trend) {
					case Trend.Upward:
						trendPercentage = 0.3;
						break;
					case Trend.Downward:
						trendPercentage = 0.7;
						break;
					default:  // Random
						trendPercentage = 0.5;
						break;
				}

				// Get the first amount
				var delta = Convert.ToDouble(trendPercentage) * this.StepRange;
				var step = Convert.ToDouble(random.NextDouble()) * this.StepRange;
				var firstAmount = (presetAmounts != null ? presetAmounts[0] : this.StartAmount + step - delta);
				this.Add(this.CreateData(random, 0, timePeriod, date, firstAmount));
				
				switch (timePeriod) {
					case TimePeriod.Month:
						date = date.AddMonths(1);
						break;
					case TimePeriod.Week:
						date = date.AddDays(7);
						break;
					default:  // Year
						date = date.AddYears(1);
						break;
				}

				for (int index = 1; index < resolvedDataPointCount; index++) {
					step = Convert.ToDouble(random.NextDouble()) * this.StepRange;
					var amount = (presetAmounts != null ? presetAmounts[index] : this[index - 1].Amount + step - delta);

					if (!this.AllowNegativeNumbers)
						amount = Math.Max(0, amount);

					this.Add(this.CreateData(random, index, timePeriod, date, amount));

					switch (timePeriod) {
						case TimePeriod.Month:
							date = date.AddMonths(1);
							break;
						case TimePeriod.Week:
							date = date.AddDays(7);
							break;
						default:  // Year
							date = date.AddYears(1);
							break;
					}
				}
			}
			finally {
				this.EndUpdate();
			}
		}

19 View Source File : SolarHalfYear.cs
License : MIT License
Project Creator : 6tail

public SolarHalfYear next(int halfYears)
        {
            if (0 == halfYears)
            {
                return new SolarHalfYear(year, month);
            }
            DateTime c = ExactDate.fromYmd(year, month, 1);
            c = c.AddMonths(MONTH_COUNT * halfYears);
            return new SolarHalfYear(c);
        }

19 View Source File : SolarSeason.cs
License : MIT License
Project Creator : 6tail

public SolarSeason next(int seasons)
        {
            if (0 == seasons)
            {
                return new SolarSeason(year, month);
            }
            DateTime c = ExactDate.fromYmd(year, month, 1);
            c = c.AddMonths(MONTH_COUNT * seasons);
            return new SolarSeason(c);
        }

19 View Source File : UserStatsGetter.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<UserYearlyCountListStats> GetUsersCountOverTwoYears()
        {
            // end Date 6/4/ 2020
            // start date 1/1/2019
            // the stats will
            // CurrentYear : 1/1/20, 1/2/20, 1/3/20, 1/4/20, 1/5/20 = 0, 1/6/20 = 0, 1/7/20 = 0, ...
            // PreviousYear: 1/1/19, 1/2/19, 1/3/19, 1/4/19, 1/5/19 = x, 1/6/20 = y, 1/7/19 = z, ...
            var startDate = DateTime.UtcNow.AddYears(-1).AddMonths(-DateTime.UtcNow.Month + 1).AddDays(-DateTime.UtcNow.Day + 1).Date;
            var endDate = DateTime.UtcNow.Date;

            var usersMonthly = (from u in _usersRepo.Table
                                where u.CreatedAt >= startDate && u.CreatedAt <= endDate
                                group u by new
                                {
                                    u.CreatedAt.Year,
                                    u.CreatedAt.Month
                                } into g
                                select new
                                {
                                    Count = g.Count(),
                                    MonthYear = new DateTime(g.Key.Year, g.Key.Month, 1)
                                }).ToList();

            var months = Enumerable.Range(0, 24).Select(offset => startDate.AddMonths(offset)).ToList();

            months.ForEach(month =>
            {
                if (!usersMonthly.Any(u => u.MonthYear.Year == month.Year && u.MonthYear.Month == month.Month))
                {
                    usersMonthly.Add(new
                    {
                        Count = 0,
                        MonthYear = month,
                    });
                }
            });

            return new UserYearlyCountListStats()
            {
                CurrentYear = usersMonthly.Where(um => um.MonthYear.Year == DateTime.UtcNow.Year).OrderBy(c => c.MonthYear).Select(c => c.Count).ToList(),
                PreviousYear = usersMonthly.Where(um => um.MonthYear.Year == DateTime.UtcNow.Year - 1).OrderBy(c => c.MonthYear).Select(c => c.Count).ToList()
            };
        }

19 View Source File : SalesDataGenerator.cs
License : MIT License
Project Creator : Actipro

protected override ICollection<SalesData> Generate() {
			// Create the results
			List<SalesData> results = new List<SalesData>();

			if (this.Options != null) {
				// Initialize the date
				DateTime date = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).AddMonths(-this.Options.Count);

				// Initialize the results with the first data item
				results.Add(new SalesData(date, this.Options.StartAmount));
				date.AddMonths(1);

				decimal delta = Convert.ToDecimal(this.Options.TrendPercentage) * this.Options.StepRange;
				for (int index = 1; index < this.Options.Count; index++) {
					decimal step = Convert.ToDecimal(this.Random.NextDouble()) * this.Options.StepRange;
					decimal amount = results[index - 1].Amount + step - delta;

					if (!this.AllowNegativeNumbers)
						amount = Math.Max(0, amount);

					results.Add(new SalesData(date, amount));
					date = date.AddMonths(1);
				}
			}

			return results;
		}

19 View Source File : KickassParser.cs
License : MIT License
Project Creator : aivarasatk

private DateTime ParseDate(string date)
        {
            var digitEndIndex = 0;
            foreach(var c in date)
            {
                if (char.IsLetter(c))
                    break;
                digitEndIndex++;
            }

            int.TryParse(date.Substring(0, digitEndIndex), out var numberToSubtract);
            var parsedDate = DateTime.UtcNow;

            if (date.Contains("min.")) parsedDate = parsedDate.AddMinutes(-numberToSubtract);
            if (date.Contains("hour")) parsedDate = parsedDate.AddHours(-numberToSubtract);
            if (date.Contains("day")) parsedDate = parsedDate.AddDays(-numberToSubtract);
            if (date.Contains("month")) parsedDate = parsedDate.AddMonths(-numberToSubtract);
            if (date.Contains("year")) parsedDate = parsedDate.AddYears(-numberToSubtract);

            return parsedDate;
        }

See More Examples