/// <summary> /// Returns the last weekday (Financial day) of the month /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <returns>Returns DateTime object that represents the last weekday (Financial day) of the month</returns> public static DateTime LastWeekDayOfMonth(this DateTime obj) { var lastDay = new DateTime(obj.Year, obj.Month, DateTime.DaysInMonth(obj.Year, obj.Month)); for (int i = 0; i < 7; i++) { if (lastDay.AddDays(i * -1).DayOfWeek != DayOfWeek.Saturday && lastDay.AddDays(i * -1).DayOfWeek != DayOfWeek.Sunday) return lastDay.AddDays(i * -1); } return lastDay; }
/// <summary> /// Returns the first weekday (Financial day) of the month /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <returns>Returns DateTime object that represents the first weekday (Financial day) of the month</returns> public static DateTime FirstWeekDayOfMonth(this DateTime obj) { var firstDay = new DateTime(obj.Year, obj.Month, 1); for (int i = 0; i < 7; i++) { if (firstDay.AddDays(i).DayOfWeek != DayOfWeek.Saturday && firstDay.AddDays(i).DayOfWeek != DayOfWeek.Sunday) return firstDay.AddDays(i); } return firstDay; }
public DateTime?GetEndTime() { switch (Type) { case DateTimeTypeEnum.Date: return(_endTime?.AddDays(1)); case DateTimeTypeEnum.DateTime when _startTime.HasValue && _endTime.HasValue && _startTime.Value == _endTime.Value: return(_endTime?.AddDays(1)); default: return(_endTime); } }
public DateTime?GetEndTime() { switch (Type) { case DateTimeTypeEnum.Date: return(_endTime?.AddDays(1)); case DateTimeTypeEnum.DateTime when _startTime.HasValue && _endTime.HasValue && _startTime.Value == _endTime.Value: case DateTimeTypeEnum.DateTime when _endTime.HasValue && _endTime.Value.Hour == 0 && _endTime.Value.Minute == 0 && _endTime.Value.Second == 0 && _endTime.Value.Millisecond == 0: return(_endTime?.AddDays(1)); default: return(_endTime); } }
/// <summary> /// Returns the first day of week with in the month. /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <param name="dow">What day of week to find the first one of in the month.</param> /// <returns>Returns DateTime object that represents the first day of week with in the month.</returns> public static DateTime FirstDayOfWeekInMonth(this DateTime obj, DayOfWeek dow) { var firstDay = new DateTime(obj.Year, obj.Month, 1); int diff = firstDay.DayOfWeek - dow; if (diff > 0) diff -= 7; return firstDay.AddDays(diff * -1); }
public async Task <IActionResult> Search(DateTime?date, string from, string to, int maxPrice) { UsersController.CheckIfLoginAndManager(this, _context); // Keep the search variables if (date.HasValue) { ViewBag.date = date.Value.ToString("yyyy-MM-dd"); } ViewBag.from = from; ViewBag.to = to; if (maxPrice > 0) { ViewBag.maxPrice = maxPrice; } var dayAfterDate = date?.AddDays(1); return(View("Index", await _context.Ticket.Include(ticket => ticket.Flight) .ThenInclude(Flight => Flight.Airplane) .Include(ticket => ticket.Flight) .ThenInclude(Flight => Flight.SourceAirport) .Include(ticket => ticket.Flight) .ThenInclude(Flight => Flight.DestAirport) .Where(ticket => (!date.HasValue || !dayAfterDate.HasValue || (date <= ticket.Flight.Date && ticket.Flight.Date < dayAfterDate)) && (string.IsNullOrEmpty(from) || ticket.Flight.SourceAirport.Country.ToLower().Contains(from.ToLower()) || ticket.Flight.SourceAirport.City.ToLower().Contains(from.ToLower())) && (string.IsNullOrEmpty(to) || ticket.Flight.DestAirport.Country.ToLower().Contains(to.ToLower()) || ticket.Flight.DestAirport.City.ToLower().Contains(to.ToLower())) && ((maxPrice <= 0) || (maxPrice >= ticket.Price)) && (ticket.Buyer == null)) .OrderBy(ticket => ticket.Flight.Date) .ToListAsync())); }
public static DateTime InstantToDateTime(double instant, DateTime start, TimeUnits units = TimeUnits.SECONDS) { DateTime instantAsDate = start; switch (units) { case TimeUnits.YEARS: instantAsDate = start.AddYears((int)instant); break; case TimeUnits.MONTHS: instantAsDate = start.AddMonths((int)instant); break; case TimeUnits.DAYS: instantAsDate = start.AddDays(instant); break; case TimeUnits.HOURS: instantAsDate = start.AddHours(instant); break; case TimeUnits.MINUTES: instantAsDate = start.AddMinutes(instant); break; case TimeUnits.SECONDS: instantAsDate = start.AddSeconds(instant); break; } return instantAsDate; }
public DateTime?GetDate(int day, int month, int year, bool future = true, DateTime?refDate = null) { int trigger = 1; if (!future) { trigger = -1; } refDate = 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); }
public async Task <IEnumerable <UsuarioPremio> > GetRedemptions(int campanhaId, DateTime?dataInicio, DateTime?dataFim) { dataFim = dataFim?.AddDays(1).AddSeconds(-1); const string sql = @"SELECT * FROM [DotzApp]..[CPR_USUARIO_PREMIO] A (NOLOCK) INNER JOIN [DotzApp]..[CPR_USUARIO] B (NOLOCK) ON A.CPR_USUARIO_ID = B.CPR_USUARIO_ID AND B.CPR_CAMPANHA_ID = @campanhaId AND (DH_PREMIO_SELECIONADO >= @dataInicio OR @dataInicio IS NULL) AND (DH_PREMIO_SELECIONADO <= @dataFim OR @dataFim IS NULL) INNER JOIN [DotzApp]..[CPR_CAMPANHA_PRODUTO] C (NOLOCK) ON A.CPR_CAMPANHA_PRODUTO_ID = C.CPR_CAMPANHA_PRODUTO_ID INNER JOIN [DotzApp]..[WMS_PRODUTO] D (NOLOCK) ON C.WMS_PRODUTO_ID = D.PRODUTO_ID INNER JOIN [DotzApp]..[WMS_PRODUTO_FORNECEDOR] E (NOLOCK) ON D.PRODUTO_ID = E.PRODUTO_ID ORDER BY B.NOME"; return(await Connection.SqlConnection.QueryAsync <UsuarioPremio, Usuario, CampanhaProduto, Produto, ProdutoFornecedor, UsuarioPremio>(sql, map : (premio, usuario, campanhaProduto, produto, produtoFornecedor) => { premio.Usuario = usuario; premio.CampanhaProduto = campanhaProduto; premio.CampanhaProduto.Produto = produto; premio.CampanhaProduto.Produto.ProdutoFornecedor = produtoFornecedor; return premio; }, splitOn : "CPR_USUARIO_PREMIO_ID,CPR_USUARIO_ID,CPR_CAMPANHA_PRODUTO_ID,WMS_PRODUTO_ID,PRODUTO_ID", param : new { campanhaId, dataInicio, dataFim })); }
public static IList<DateTime> GetNonWorkingDays(int year) { IList<DateTime> days = new List<DateTime>(); days.Add(new DateTime(year, 01, 01)); days.Add(new DateTime(year, 01, 06)); days.Add(new DateTime(year, 04, 25)); days.Add(new DateTime(year, 05, 01)); days.Add(new DateTime(year, 06, 02)); days.Add(new DateTime(year, 06, 24)); days.Add(new DateTime(year, 08, 15)); days.Add(new DateTime(year, 10, 01)); days.Add(new DateTime(year, 12, 08)); days.Add(new DateTime(year, 12, 25)); days.Add(new DateTime(year, 12, 26)); days.Add(NonWorkingDays.EasterDay(year)); days.Add(NonWorkingDays.EasterDay(year).AddDays(1)); DateTime dummy = new DateTime(year, 1, 1); while (dummy.Year == year) { if (!days.Contains(dummy) && dummy.DayOfWeek == DayOfWeek.Saturday || dummy.DayOfWeek == DayOfWeek.Sunday) { days.Add(dummy); } dummy = dummy.AddDays(1); } return days;//a }
public DateTime GetPossibleStartNewSale(Wagon wagon) { DateTime today = DateTime.Today; //дата вступления во владение DateTime?takePossessionDate = GetLastSaleOperation(wagon)?.StartDate; //дата когда истекает срок аренды DateTime?latestRentDate = GetLatestDateRentExpiresOn(wagon); //если не было операций покупки этого вагона if (!takePossessionDate.HasValue) { return(today); } //если срок аренды вагона уже истек или по вагону не было операций аренды, то продать можно на следующий день после вступление во владение if (latestRentDate < today || !latestRentDate.HasValue) { return((takePossessionDate < today ? today : takePossessionDate?.AddDays(1)) ?? today); } //если срок аренды еще не истек - продать можно только начиная с даты когда вагон возвращается в управление владельца return(latestRentDate > takePossessionDate?latestRentDate.Value.AddDays(1) : takePossessionDate.Value.AddDays(1)); }
public static System.Collections.Generic.List <DSS3_LogisticsPoolingForUrbanDistribution.BO.OrderWMS> GenerateOrders(int?ordersCount) { using (new zAppDev.DotNet.Framework.Profiling.Profiler("OrderGenerator", zAppDev.DotNet.Framework.Profiling.AppDevSymbolType.ClassOperation, "GenerateOrders")) { System.Collections.Generic.List <DSS3_LogisticsPoolingForUrbanDistribution.BO.GeoArea> areas = new DSS3_LogisticsPoolingForUrbanDistribution.DAL.Repository().GetAll <DSS3_LogisticsPoolingForUrbanDistribution.BO.GeoArea>(); System.Collections.Generic.List <DSS3_LogisticsPoolingForUrbanDistribution.BO.Warehouse> warehouses = new DSS3_LogisticsPoolingForUrbanDistribution.DAL.Repository().GetAll <DSS3_LogisticsPoolingForUrbanDistribution.BO.Warehouse>(); System.Collections.Generic.List <DSS3_LogisticsPoolingForUrbanDistribution.BO.OrderWMS> orders = new DSS3_LogisticsPoolingForUrbanDistribution.DAL.Repository().GetAll <DSS3_LogisticsPoolingForUrbanDistribution.BO.OrderWMS>(); System.Collections.Generic.List <DSS3_LogisticsPoolingForUrbanDistribution.BO.OrderWMS> generatedOrders = new System.Collections.Generic.List <DSS3_LogisticsPoolingForUrbanDistribution.BO.OrderWMS>(); int?areasNo = (areas?.Count() ?? 0); int?ordersNo = (orders?.Count() ?? 0); int?warehousesNo = (warehouses?.Count() ?? 0); for (var i = 0; i < ordersCount; i = i + 1) { int?randomOrderIndex = zAppDev.DotNet.Framework.Utilities.Common.Random.Next(0, (ordersNo).GetValueOrDefault(0)); DSS3_LogisticsPoolingForUrbanDistribution.BO.OrderWMS tempOrder = zAppDev.DotNet.Framework.Utilities.Common.GetItemFromList(orders, randomOrderIndex.GetValueOrDefault(0)); DSS3_LogisticsPoolingForUrbanDistribution.BO.OrderWMS copyOrder = tempOrder?.Copy(false, null, true); int?randomAreaIndex = zAppDev.DotNet.Framework.Utilities.Common.Random.Next(0, (areasNo).GetValueOrDefault(0)); DSS3_LogisticsPoolingForUrbanDistribution.BO.GeoArea selectedGeoArea = zAppDev.DotNet.Framework.Utilities.Common.GetItemFromList(areas, randomAreaIndex.GetValueOrDefault(0)); copyOrder.OrdDlsAddress = ""; copyOrder.OrdDlsCity = (selectedGeoArea?.Area ?? ""); copyOrder.OrdDlsArea = (selectedGeoArea?.County ?? ""); copyOrder.OrdDlsZipCode = (selectedGeoArea?.PostalCode ?? ""); int?randomWarehouseIndex = zAppDev.DotNet.Framework.Utilities.Common.Random.Next(0, (warehousesNo).GetValueOrDefault(0)); DSS3_LogisticsPoolingForUrbanDistribution.BO.Warehouse warehouse = zAppDev.DotNet.Framework.Utilities.Common.GetItemFromList(warehouses, randomWarehouseIndex.GetValueOrDefault(0)); System.Collections.Generic.List <DSS3_LogisticsPoolingForUrbanDistribution.BO.RegionalAgent> regionalAgents = new DSS3_LogisticsPoolingForUrbanDistribution.DAL.Repository().Get <DSS3_LogisticsPoolingForUrbanDistribution.BO.RegionalAgent>((ra) => ra.AreaSupport.Contains(selectedGeoArea)); int?randomRAIndex = zAppDev.DotNet.Framework.Utilities.Common.Random.Next(0, (regionalAgents?.Count() ?? 0)); DSS3_LogisticsPoolingForUrbanDistribution.BO.RegionalAgent regionalAgent = zAppDev.DotNet.Framework.Utilities.Common.GetItemFromList(regionalAgents, randomRAIndex.GetValueOrDefault(0)); copyOrder.OrdAgencyCode = (regionalAgent?.AgencyCode ?? ""); copyOrder.OrdAgencyAddress = (regionalAgent?.AgencyAddress ?? ""); copyOrder.OrdAgencyDescr = (regionalAgent?.AgencyDescription ?? ""); DateTime?now = DateTime.UtcNow; copyOrder.OrdRegDateTime = now; int?randomDaysAdd = zAppDev.DotNet.Framework.Utilities.Common.Random.Next(1, 100); copyOrder.OrdDeliveryDateTime = (now?.AddDays((randomDaysAdd).GetValueOrDefault(0)) ?? System.Data.SqlTypes.SqlDateTime.MinValue.Value); copyOrder.OrdStatus = 10; generatedOrders?.Add(copyOrder); new DSS3_LogisticsPoolingForUrbanDistribution.DAL.Repository().Save <DSS3_LogisticsPoolingForUrbanDistribution.BO.OrderWMS>(copyOrder); } return(generatedOrders); } }
private void DownloadAttachements(MessageCollection messages, DateTime?since = null, DateTime?before = null) { string criteria = ""; if (since != null) { criteria += $"SENTSINCE {since?.ToString("dd-MMM-yyy", CultureInfo.InvariantCulture)}"; } if (before != null) { criteria += $" SENTBEFORE {before?.ToString("dd-MMM-yyy", CultureInfo.InvariantCulture)}"; } if (criteria != "") { messages.Download(criteria); } else { messages.Download(); } Queue <AttachementStruct> attachementQueue = new Queue <AttachementStruct>(); bool sheetHasBeenInserted = false; AttachementStruct attExt = new AttachementStruct(); string basename = Path.GetFileNameWithoutExtension(config.loadingFilename); foreach (Message message in messages) { Console.WriteLine($"MESSAGE FROM: {message.From.Address.ToString()} {message.Date:yyyy-MM-dd}"); Console.WriteLine($"ATT LENGTH: {message.Attachments.Length} RSC LENGTH: {message.EmbeddedResources.Length}"); var attachements = (message.Attachments.Length > 0) ? message.Attachments : message.EmbeddedResources; foreach (var attachment in attachements) { attachment.Download(); attExt.attachment = attachment; if (attachment.FileName == config.loadingFilename) { DateTime?date = message.Date; date = date?.AddDays(1); string filedate = date?.ToString("yyyy-MM-dd"); attExt.newFilename = $"{basename} {filedate}.txt"; attachementQueue.Enqueue(attExt); } else if (attachment.FileName == config.sheetFilename && !sheetHasBeenInserted) { attExt.newFilename = attachment.FileName.Replace("ç", ""); attachementQueue.Enqueue(attExt); sheetHasBeenInserted = true; } } Console.WriteLine(); } foreach (AttachementStruct att in attachementQueue) { att.attachment.Save(attachmentsDirPath, att.newFilename); } }
public bool TryConvertToDateTimeRange(out DateTime?dateTimeStart, out DateTime?dateTimeEnd) { dateTimeStart = null; dateTimeEnd = null; if (!ParseDateStrings(out int parsedYear, out int parsedMonth, out int parsedDay)) { return(false); } try { dateTimeStart = new DateTime(parsedYear, parsedMonth, parsedDay); if (!string.IsNullOrEmpty(Day)) { dateTimeEnd = dateTimeStart?.AddDays(1); } else if (!string.IsNullOrEmpty(Month)) { dateTimeEnd = dateTimeStart?.AddMonths(1); } else { dateTimeEnd = dateTimeStart?.AddYears(1); } return(true); } catch (ArgumentOutOfRangeException) { return(false); } }
/// <summary> /// Method for Week Days /// </summary> /// <param name="startDateRange">dateTime value</param> /// <param name="endDateRange">endDateTime value</param> /// <returns></returns> public SelectionRange GetTotalWeekDays(DateTime startDateRange, DateTime?endDateRange = null) { if (endDateRange == null) { var days = DayOfWeek.Sunday - startDateRange.DayOfWeek; var startDate = startDateRange.AddDays(days); ObservableCollection <DateTime> dates = new ObservableCollection <DateTime>(); for (var i = 0; i < 7; i++) { dates.Add(startDate.Date); startDate = startDate.AddDays(1); } return(new SelectionRange(dates[0], dates[dates.Count - 1])); } else { ObservableCollection <DateTime> dates = new ObservableCollection <DateTime>(); var startDayOfWeek = DayOfWeek.Sunday - startDateRange.DayOfWeek; var startDate = startDateRange.AddDays(startDayOfWeek); var endDayOfWeek = DayOfWeek.Saturday - endDateRange?.DayOfWeek; var endDate = endDateRange?.AddDays((int)endDayOfWeek); var difference = (endDate - startDate); for (var i = 0; i < ((TimeSpan)difference).Days + 1; i++) { dates.Add(startDate.Date); startDate = startDate.AddDays(1); } return(new SelectionRange(dates[0], dates[dates.Count - 1])); } }
private static DateTime?GetDate(DateTime?lastDT) { DateTime?nextDT = lastDT?.AddDays(1); return((nextDT < DateTime.Now) ? nextDT : null); }
static void Main(string[] args) { Person person = null; var name = person?.FirstName?.ToLower(); DateTime?now = DateTime.Now; var tomorrow = now?.AddDays(1); }
/// <summary> /// Returns true if this date is in between (inclusive) the given dates. /// This method differs from IsBetweenDateTimes in that onOrAfterDate and onOrBeforeDate must be dates only /// (an exception will be thrown if time information is passed - use .Date if you have to.) /// and that it is inclusive on both ends of the range. /// This method also correctly returns true in the case where the dateTime parameter is 3:30PM on 11/15/09 and the /// onOrBeforeDate is 11/15/09. /// If you want to define a range with time information, use IsBetweenDateTimes instead. /// Passing null for either of the two dates is considered to be infinity in that direction. Therefore, passing null for /// both dates will always result in true. /// </summary> public static bool IsBetweenDates(this DateTime dateTime, DateTime?onOrAfterDate, DateTime?onOrBeforeDate) { assertDateTimeHasNoTime(onOrAfterDate, "on or after date"); assertDateTimeHasNoTime(onOrBeforeDate, "on or before date"); onOrBeforeDate = onOrBeforeDate?.AddDays(1); return(IsBetweenDateTimes(dateTime, onOrAfterDate, onOrBeforeDate)); }
private int FirstMonday(int Year, int Month) { DateTime FirstMonday = new DateTime(Year, Month, 1); while (!(FirstMonday.DayOfWeek == DayOfWeek.Monday)) { FirstMonday = FirstMonday.AddDays(1); } return FirstMonday.Day; }
private static PageTuple GetPageTup(PageRequest req, DateTime?lastModif, int num) { string response = "page " + num; DateTime?nextModif = (lastModif < DateTime.Now) ? lastModif?.AddDays(1) : null; PageTuple pageTup = new PageTuple(response, nextModif); return(pageTup); }
/// <summary> /// Returns the last day of week with in the month. /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <param name="dow">What day of week to find the last one of in the month.</param> /// <returns>Returns DateTime object that represents the last day of week with in the month.</returns> public static DateTime LastDayOfWeekInMonth(this DateTime obj, DayOfWeek dow) { var lastDay = new DateTime(obj.Year, obj.Month, DateTime.DaysInMonth(obj.Year, obj.Month)); DayOfWeek lastDow = lastDay.DayOfWeek; int diff = dow - lastDow; if (diff > 0) diff -= 7; return lastDay.AddDays(diff); }
public void CanAddDaysAcrossDstTransition_LandInOverlap() { var tz = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); var dt = new DateTime(2015, 10, 31, 1, 30, 0); var result = dt.AddDays(1, tz); var expected = new DateTimeOffset(2015, 11, 1, 1, 30, 0, TimeSpan.FromHours(-7)); Assert.Equal(expected, result); Assert.Equal(expected.Offset, result.Offset); }
public void CanAddDaysAcrossDstTransition_StartWithMismatchedKind() { var tz = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); var dt = new DateTime(2015, 3, 8, 8, 0, 0, DateTimeKind.Utc); var result = dt.AddDays(1, tz); var expected = new DateTimeOffset(2015, 3, 9, 0, 0, 0, TimeSpan.FromHours(-7)); Assert.Equal(expected, result); Assert.Equal(expected.Offset, result.Offset); }
/// <summary> /// Выходит ли сегодня за интервал расписания группы. /// Нужно для фильтрации не начавшегося или прошедшего расписания. /// </summary> /// <param name="group">Группа для проверки</param> /// <returns>false если расписание группы актуально на сегодня</returns> private static bool IsGroupOutInterval(Group group) { DateTime?startDate = group.ScheduleDateFrom; DateTime?endDate = group.ScheduleDateTo; // При сравнении периода, отнимаем 3 дня в начале периода. // Это сделано для того чтобы можно было знать о расписании за 3 дня. startDate = startDate?.AddDays(-3); return(!TodayIsInRange(startDate, endDate)); }
private int LastSunday(int Year, int Month) { int LastDay = DateTime.DaysInMonth(Year, Month); DateTime LastSunday = new DateTime(Year, Month, LastDay); while (!(LastSunday.DayOfWeek == DayOfWeek.Sunday)) { LastSunday = LastSunday.AddDays(-1); } return LastSunday.Day; }
public async Task <SearchResult <InventoryDailyReportViewModel> > Search(string tenantId, string userId, string warehouseId, string keyword, DateTime?fromDate, DateTime?toDate, int page, int pageSize) { if (string.IsNullOrEmpty(warehouseId)) { return(new SearchResult <InventoryDailyReportViewModel>(-1, _sharedResourceService.GetString(ValidatorMessage.PleaseSelect, _resourceService.GetString("warehouse")))); } if (!fromDate.HasValue) { fromDate = DateTime.Today; } toDate = toDate?.AddDays(1).AddMilliseconds(-1) ?? fromDate.Value.AddDays(1).AddMilliseconds(-1); // Check current user is warehouse manager. var isWarehouseManager = await _warehouseManagerConfigRepository.CheckExists(warehouseId, userId, tenantId); if (!isWarehouseManager) { return(new SearchResult <InventoryDailyReportViewModel>(-403, _sharedResourceService.GetString(ErrorMessage.NotHavePermission))); } var inventoryDailyReports = await _inventoryDailyReportRepository.SearchInventoryOpningStock(tenantId, keyword, warehouseId, fromDate.Value, page, pageSize, out int totalRows); // Lấy về danh sách nhập trong kỳ. if (!inventoryDailyReports.Any()) { return(new SearchResult <InventoryDailyReportViewModel>(inventoryDailyReports, totalRows)); } foreach (var inventoryDailyReport in inventoryDailyReports) { // Lấy về tổng nhập trong kỳ. var receivingInPeriod = _goodsReceiptNoteDetailRepository.GetReceivingInPeriod(tenantId, warehouseId, inventoryDailyReport.ProductId, fromDate.Value, toDate.Value); // Lấy về tổng xuất trong kỳ. var deliveringInPeriod = _goodsDeliveryNoteDetailRepository.GetDeliveringInPeriod(tenantId, warehouseId, inventoryDailyReport.ProductId, fromDate.Value, toDate.Value); inventoryDailyReport.ReceivingQuantity = receivingInPeriod.Quantity; inventoryDailyReport.ReceivingValue = receivingInPeriod.Value; inventoryDailyReport.DeliveringQuantity = deliveringInPeriod.Quantity; inventoryDailyReport.DeliveringValue = deliveringInPeriod.Value; inventoryDailyReport.ClosingStockQuantity = inventoryDailyReport.OpeningStockQuantity + receivingInPeriod.Quantity - deliveringInPeriod.Quantity; inventoryDailyReport.ClosingStockValue = inventoryDailyReport.OpeningStockValue + receivingInPeriod.Value - deliveringInPeriod.Value; } return(new SearchResult <InventoryDailyReportViewModel>(inventoryDailyReports, totalRows)); }
public ActionResult Search(string content, string title, DateTime?date) { var dayAfterDate = date?.AddDays(1); return(View(Db.Reviews .Where(review => (!string.IsNullOrEmpty(content) && review.Content.ToLower().Contains(content.ToLower())) || (!string.IsNullOrEmpty(title) && review.Title.ToLower().Contains(title.ToLower())) || (date.HasValue && dayAfterDate.HasValue && date < review.CreationDate && review.CreationDate < dayAfterDate)) .OrderByDescending(x => x.CreationDate) .ToList())); }
public Task <List <GoodsReceiptNoteViewModel> > Search(string tenantId, string userId, string supplierId, string deliverId, string warehouseId, DateTime?fromDate, DateTime?toDate, int page, int pageSize, out int totalRows) { toDate = toDate?.AddDays(1).AddMilliseconds(-1); var query = from grn in Context.Set <GoodsReceiptNote>() join w in Context.Set <Warehouse>() on grn.WarehouseId equals w.Id join gd in Context.Set <GoodsDeliver>() on grn.DeliverId equals gd.Id into ggrngd from gdg in ggrngd.DefaultIfEmpty() join wmc in Context.Set <WarehouseManagerConfig>() on grn.WarehouseId equals wmc.WarehouseId join s in Context.Set <Supplier>() on grn.SupplierId equals s.Id into gj from gs in gj.DefaultIfEmpty() where grn.TenantId == tenantId && !grn.IsDelete && wmc.UserId == userId && (string.IsNullOrEmpty(supplierId) || grn.SupplierId == supplierId) && (string.IsNullOrEmpty(warehouseId) || grn.WarehouseId == warehouseId) && (string.IsNullOrEmpty(deliverId) || grn.DeliverId == deliverId) && (!fromDate.HasValue || fromDate <= grn.EntryDate) && (!toDate.HasValue || toDate >= grn.EntryDate) select new GoodsReceiptNoteViewModel { Id = grn.Id, Type = grn.Type, CreatorId = grn.CreatorId, CreatorFullName = grn.CreatorFullName, CreatorAvatar = grn.CreatorAvatar, DeliverId = grn.DeliverId, DeliverFullName = gdg.FullName, DeliverPhoneNumber = gdg.PhoneNumber, SupplierId = gs.Id, SupplierName = gs.Name, WarehouseId = w.Id, WarehouseName = w.Name, EntryDate = grn.EntryDate, CreateTime = grn.CreateTime, InvoiceDate = grn.InvoiceDate, InvoiceNo = grn.InvoiceNo, ReceiptNo = grn.ReceiptNo, ReceiverFullName = grn.ReceiverFullName, ReceiverId = grn.ReceiverId, TotalAmounts = grn.TotalAmounts, TotalItems = grn.TotalItems, Day = grn.Day, Month = grn.Month, Year = grn.Year }; totalRows = query.Count(); return(query .OrderByDescending(x => x.EntryDate) .Skip((page - 1) * pageSize) .Take(pageSize) .ToListAsync()); }
public async Task <IEnumerable <Reserva> > Listar(ReservaEstadoEnum?estado, DateTime?checkInDesde, DateTime?checkInHasta, DateTime?checkOutDesde, DateTime?checkOutHasta) { var ultimaNocheDesde = checkOutDesde?.AddDays(-1); var ultimaNocheHasta = checkOutHasta?.AddDays(-1); return(await _context.Reservas.Include(x => x.PasajeroTitular) .Where(x => estado == null || x.Estado.Equals(estado)) .Where(x => checkInDesde == null || x.PrimeraNoche >= checkInDesde) .Where(x => checkInHasta == null || x.PrimeraNoche <= checkInHasta) .Where(x => ultimaNocheDesde == null || x.UltimaNoche >= ultimaNocheDesde) .Where(x => ultimaNocheHasta == null || x.UltimaNoche <= ultimaNocheHasta) .ToListAsync()); }
public async Task <IEnumerable <ScheduleViewModel> > GetByRange(DateTime start, DateTime?end = null) { var endTime = end?.AddDays(1) ?? start.AddMonths(2); var models = await _scheduleRepository.All.Where(x => x.UserName == UserName && ((x.Start <= start && x.End >= start) || (x.Start >= start && x.End < endTime) || (x.Start < endTime && x.End >= endTime) || (x.Start <= start && x.End >= endTime))).OrderBy(x => x.Start).ToListAsync(); var viewModels = Mapper.Map <IEnumerable <Schedule>, IEnumerable <ScheduleViewModel> >(models); return(viewModels); }
/// <summary> /// Main loop to get pictures /// </summary> /// <param name="days"></param> static void loopToPast(int?days) { DateTime?dt = DateTime.Now; int count = 0; StringBuilder html = new StringBuilder(); html.AppendLine("<HTML>"); html.AppendLine(" <HEAD>"); html.AppendLine(" <TITLE>NASA :: Astronomic Picture of the Day</TITLE>"); html.AppendLine(" <meta charset='UTF-8'>"); html.AppendLine(" <meta name='description' content='Comemorative app to NASA Astronomic Picture of the Day 25 years'>"); html.AppendLine(" <meta name='keywords' content='NASA, APOD, Astronomic, Picture, Day'>"); html.AppendLine(" <meta name='author' content='NASA'>"); html.AppendLine(" <meta name='viewport' content='width=device-width, initial-scale=1.0'>"); html.AppendLine(" <link href='https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css' rel='stylesheet' integrity='sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk' crossorigin='anonymous'>"); html.AppendLine(" <script src='https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js' integrity='sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI' crossorigin='anonymous'></script>"); html.AppendLine(" <script src='https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.bundle.min.js' integrity='sha384-1CmrxMRARb6aLqgBO7yyAxTOQE2AKb9GfXnEo760AUcUmFx3ibVJJAzGytlQcNXd' crossorigin='anonymous'></script>"); html.AppendLine(" <link href='https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css' rel='stylesheet'>"); html.AppendLine(" <link href='https://stackpath.bootstrapcdn.com/bootswatch/4.5.0/superhero/bootstrap.min.css' rel='stylesheet'>"); html.AppendLine(" <script src='https://stackpath.bootstrapcdn.com/bootlint/1.1.0/bootlint.min.js'></script>"); html.AppendLine(" <STYLE>"); html.AppendLine(" .nasaDay{ padding: 20px; } "); html.AppendLine(" .nasaDate{ font-weight:bold; } "); html.AppendLine(" .nasaTitle{ font-weight:bold; } "); html.AppendLine(" .nasaExplanation{ text-align: justify; text-justify: inter - word; padding-top: 10px; padding-bottom: 10px; } "); html.AppendLine(" .nasaCopyright{ font-style:italic; } "); html.AppendLine(" .nasaImage{} "); html.AppendLine(" .nasaPic{ width:100% } "); html.AppendLine(" .nasaVideo{} "); html.AppendLine(" </STYLE>"); html.AppendLine(" </HEAD>"); html.AppendLine(" <BODY>"); while (count != days) { NasaAPOD apod = _nasaService.getAPOD(false, dt); string htmlSection = SaveAPOD(apod, dt); html.AppendLine(htmlSection); dt = dt?.AddDays(-1); count++; } html.AppendLine(" </BODY>"); html.AppendLine("</HTML>"); System.IO.File.WriteAllText(@".\NasaAPOD.html", html.ToString()); Console.WriteLine(@"Webpage .\NasaAPOD.html generated with all range images."); }
private static int GetNumberOfBusinessDays(DateTime?start, DateTime stop) { int days = 0; while (start <= stop) { if (start?.DayOfWeek != DayOfWeek.Saturday && start?.DayOfWeek != DayOfWeek.Sunday) { ++days; } start = start?.AddDays(1); } return(days); }
/// <summary> /// 2019-05-31 转换为 2019-06-01 /// </summary> /// <param name="dateTime"></param> /// <returns></returns> public static DateTime?GetDateTimeAddOneDay(DateTime?dateTime) { DateTime?result = null; if (dateTime == null || dateTime == DateTime.MinValue || dateTime == DateTime.MaxValue) { result = null; } else { result = dateTime?.AddDays(1); } return(result); }
public static DateTimeOffset Default(DateTime dt, TimeZoneInfo timeZone) { if (dt.Kind != DateTimeKind.Unspecified) { var dto = new DateTimeOffset(dt); return TimeZoneInfo.ConvertTime(dto, timeZone); } if (timeZone.IsAmbiguousTime(dt)) { var earlierOffset = timeZone.GetUtcOffset(dt.AddDays(-1)); return new DateTimeOffset(dt, earlierOffset); } if (timeZone.IsInvalidTime(dt)) { var earlierOffset = timeZone.GetUtcOffset(dt.AddDays(-1)); var laterOffset = timeZone.GetUtcOffset(dt.AddDays(1)); var transitionGap = laterOffset - earlierOffset; return new DateTimeOffset(dt.Add(transitionGap), laterOffset); } return new DateTimeOffset(dt, timeZone.GetUtcOffset(dt)); }
public static bool 今天的签退区间(this WeixinWorkPlanDetail item, out DateTime?begin, out DateTime?end) { var now = DateTime.Now; if (!item.指定日期的签退起止(now, out begin, out end)) { return(false); } if (now <= begin) // 比最早时间早,说明在第二天,那就要返回前一天的区间 { begin = begin?.AddDays(-1); end = end?.AddDays(-1); } return(true); }
private async Task <ICollection <CommitInfo> > GetCommitInfo( Guid repositoryId, IEnumerable <GitRepositoryApiResponse> repositories, IEnumerable <TeamMemberApiResponse> teamMembers, DateTime?fromDate, DateTime?toDate) { toDate = toDate?.AddDays(1); var branches = await _gitApi.GetBranchList(Convert.ToString(repositoryId)); var commitsTasks = branches.BranchNames .Select(async x => await _gitApi.GetCommitList(Convert.ToString(repositoryId), fromDate, toDate, x)) .ToList(); await Task.WhenAll(commitsTasks); var commits = commitsTasks .SelectMany(x => x.Result.Value) .Distinct(x => x.CommitId) .Where(x => x.Author.Email == x.Committer.Email) .ToList(); var commitDetailsTasks = commits .Select(async x => await _gitApi.GetCommit(Convert.ToString(repositoryId), x.CommitId, 1)) .ToList(); await Task.WhenAll(commitDetailsTasks); var commitDetails = commitDetailsTasks.Select(x => x.Result).ToList(); return((from commit in commits join t in teamMembers on commit.Author.Email equals t.UniqueName into t join r in repositories on repositoryId equals r.Id into r join c in commitDetails on commit.CommitId equals c.CommitId into c from teamMember in t.DefaultIfEmpty(UnknownTeamMember) from repository in r from commitDetail in c.DefaultIfEmpty() where commitDetail == null || commitDetail?.Parents.Count < 2 && (fromDate == null || commitDetail?.Author.Date >= fromDate) && (toDate == null || commitDetail?.Author.Date < toDate) select new CommitInfo(commitDetail ?? commit, teamMember, repository)) .ToList()); }
private void SetMarksToAttendanceMarks(DateTime?startDate, DateTime?endDate, string mark) { DateTime lastDayOfMonth = new DateTime(Year, Month, DateTime.DaysInMonth(Year, Month)); var attendanceMarks = AttendanceMarks; while ((startDate <= endDate) && (startDate <= lastDayOfMonth)) { if (startDate?.Month == Month) { attendanceMarks[(int)startDate?.Day - 1] = mark; } startDate = startDate?.AddDays(1); } AttendanceMarks = attendanceMarks; }
public async Task <AthleteDto> GetDietStatsAsync(int userId, DateTime?date) { if (date is null) { date = DateTime.Today; } var start = date; var end = date?.AddDays(1); var athlete = await _athleteRepository.FindByCondition(a => a.UserId == userId, include : source => source.Include(a => a.AthleteDietStats .Where(ads => ads.DateCreated >= start && ads.DateCreated <= end)).ThenInclude(ads => ads.DietStat)); return(_mapper.Map <AthleteDto>(athlete)); }
public async Task <FileResult> GetGiftCertificatesWithOrderInfoReportFile([FromQuery] string from, [FromQuery] string to, [FromQuery] int?type = null, [FromQuery] int?status = null, [FromQuery] string billinglastname = null, [FromQuery] string shippinglastname = null, [FromQuery] bool notzerobalance = false) { DateTime?dFrom = !string.IsNullOrEmpty(from) ? from.GetDateFromQueryStringInPst(TimeZoneHelper.PstTimeZoneInfo) : null; DateTime?dTo = !string.IsNullOrEmpty(to) ? to.GetDateFromQueryStringInPst(TimeZoneHelper.PstTimeZoneInfo) : null; GCFilter filter = new GCFilter() { From = dFrom, To = dTo?.AddDays(1) ?? dTo, Type = type.HasValue ? (GCType?)type.Value : null, StatusCode = status.HasValue ? (RecordStatusCode?)status.Value : null, BillingAddress = !String.IsNullOrEmpty(billinglastname) ? new CustomerAddressFilter() { LastName = billinglastname }: null, ShippingAddress = !String.IsNullOrEmpty(shippinglastname) ? new CustomerAddressFilter() { LastName = shippinglastname } : null, NotZeroBalance = notzerobalance, }; filter.Paging = null; var data = await GCService.GetGiftCertificatesWithOrderInfoAsync(filter); foreach (var item in data.Items) { item.Created = TimeZoneInfo.ConvertTime(item.Created, TimeZoneInfo.Local, TimeZoneHelper.PstTimeZoneInfo); } var result = _gCWithOrderListItemModelCsvMapCSVExportService.ExportToCsv(data.Items); var contentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = String.Format(FileConstants.GIFT_CERTIFICATES_REPORT_STATISTIC, DateTime.Now) }; Response.Headers.Add("Content-Disposition", contentDisposition.ToString()); return(File(result, "text/csv")); }
public ActionResult Get( [FromRoute] string id, [FromQuery] DateTime?beginDate, [FromQuery] DateTime?endDate, [FromQuery] int?memberNumber ) { endDate = endDate?.AddDays(1); // date passed by TS does not reflect desired range, and is of type string... var result = serv.getQuery( new Service.DTO.SearchOptions { idOrName = id, endDate = endDate, beginDate = beginDate, dwccardnum = memberNumber }); return(new JsonResult(new { data = result })); }
private Status VerificoVencimiento(DateTime?date, int diasDeAviso) { //DateTime startDateTime = DateTime.Today; //Today at 00:00:00 DateTime endDateTime = DateTime.Today.AddDays(1).AddTicks(-1); //Today at 23:59:59 if (date?.AddDays(1).AddTicks(-1) < endDateTime) { return(Status.Vencido); } if (date <= (endDateTime.AddDays(diasDeAviso))) { return(Status.PorVencer); } else { return(Status.Correcto); } }
/// <summary> /// 在C#中指定修订号为*的时候,修订号则是一个时间戳,我们可以从其得到编译日期 /// 生成和修订版本号必须是自动生成的 /// AssemblyInfo里的写法应该为1.0之后为.* /// [assembly: AssemblyVersion("1.0.*")] /// </summary> /// <returns></returns> public DateTime GetBuildDateTime() { /* * version = 1.0.3420.56234 * 这里主版本号是1,次版本号是0,而生成和修订版本号是自动生成的。 * 使用*时,生成号是从2000年1月1日开始的天数,而修订号是从凌晨开始的秒数除以2。 */ string version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); int days = 0; int seconds = 0; string[] v = version.Split('.'); if (v.Length == 4) { days = Convert.ToInt32(v[2]); seconds = Convert.ToInt32(v[3]); } DateTime dt = new DateTime(2000, 1, 1); dt = dt.AddDays(days); dt = dt.AddSeconds(seconds * 2); return dt; }
/// <summary> /// Performs addition of a date time and a time span in a global context. /// </summary> /// <param name="value">The value.</param> /// <param name="timeSpan">The time span.</param> /// <returns>The DateTime after incrementing by TimeSpan.</returns> public virtual DateTime OnIncrement(DateTime value, TimeSpan timeSpan) { // special case: value is at DateTime.MaxValue if (DateTime.MaxValue.Date == value.Date && value.TimeOfDay.Add(timeSpan) > TimeSpan.FromDays(1)) { return value.AddDays(-1).Add(timeSpan); } return value.Add(timeSpan); }
private static DateTime NextDay(DateTime date) { return date.AddDays(1); }
protected virtual void InitOptions() { PreProcessing = null; OnBegin = null; OnEnd = null; //AtStart = null; //AtEnd = null; CreateInputFiles = true; SetupRunPeriod = true; simLenght = 14.0; //14 days start = DateTime.Today; end = start.AddDays(simLenght); StartTAG = "<<start>>"; EndTAG = "<<end>>"; CheckRun = true; SuccessString = "successfully terminated"; SimDirectory = new FilePath(); DataDirectory = new FilePath("data"); SaveOutput = true; WorkingDirectory = new FilePath(); OutputFile = new FileName("output.txt"); Executable = new FileName(SimDirectory.Path + "mohid.exe"); Verbose = false; templateFiles = new List<InputFileTemplate>(); }
private int GetWeekOfYearFullDays(DateTime time, int firstDayOfWeek, int fullDays) { int dayForJan1; int offset; int day; int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. // // Calculate the number of days between the first day of year (1/1) and the first day of the week. // This value will be a positive value from 0 ~ 6. We call this value as "offset". // // If offset is 0, it means that the 1/1 is the start of the first week. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 12/31 1/1 1/2 1/3 1/4 1/5 1/6 // +--> First week starts here. // // If offset is 1, it means that the first day of the week is 1 day ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 // +--> First week starts here. // // If offset is 2, it means that the first day of the week is 2 days ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sat Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 1/8 // +--> First week starts here. // Day of week is 0-based. // Get the day of week for 1/1. This can be derived from the day of week of the target day. // Note that we can get a negative value. It's ok since we are going to make it a positive value when calculating the offset. dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7); // Now, calculate the offset. Subtract the first day of week from the dayForJan1. And make it a positive value. offset = (firstDayOfWeek - dayForJan1 + 14) % 7; if (offset != 0 && offset >= fullDays) { // // If the offset is greater than the value of fullDays, it means that // the first week of the year starts on the week where Jan/1 falls on. // offset -= 7; } // // Calculate the day of year for specified time by taking offset into account. // day = dayOfYear - offset; if (day >= 0) { // // If the day of year value is greater than zero, get the week of year. // return (day / 7 + 1); } // // Otherwise, the specified time falls on the week of previous year. // Call this method again by passing the last day of previous year. // // the last day of the previous year may "underflow" to no longer be a valid date time for // this calendar if we just subtract so we need the subclass to provide us with // that information if (time <= MinSupportedDateTime.AddDays(dayOfYear)) { return GetWeekOfYearOfMinSupportedDateTime(firstDayOfWeek, fullDays); } return (GetWeekOfYearFullDays(time.AddDays(-(dayOfYear + 1)), firstDayOfWeek, fullDays)); }
/// <summary> /// Get the previous working based on the project calendar. /// </summary> /// <param name="day">The day to get the previous day for.</param> /// <returns>The previous day.</returns> public DateTime GetPreviousWorkingDay(DateTime day) { DateTime previousDay = day.AddDays(-1); while (!IsWorkingDay(previousDay)) previousDay = previousDay.AddDays(-1); return previousDay; }
/// <summary> /// Returns a given datetime according to the week of year and the specified day within the week. /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <param name="week">A number of whole and fractional weeks. The value parameter can only be positive.</param> /// <param name="dayofweek">A DayOfWeek to find in the week</param> /// <returns>A DateTime whose value is the sum according to the week of year and the specified day within the week.</returns> public static DateTime GetDateByWeek(this DateTime obj, int week, DayOfWeek dayofweek) { if (week > 0 && week < 54) { var firstDayOfyear = new DateTime(obj.Year, 1, 1); int daysToFirstCorrectDay = (((int)dayofweek - (int)firstDayOfyear.DayOfWeek) + 7) % 7; return firstDayOfyear.AddDays(7 * (week - 1) + daysToFirstCorrectDay); } return obj; }
private int GetWeekOfYearFullDays(DateTime time, CalendarWeekRule rule, int firstDayOfWeek, int fullDays) { GregorianCalendar gregorianCalendar = new GregorianCalendar(); // Make the day of year to be 0-based, so that 1/1 is day 0. int dayOfYear = gregorianCalendar.GetDayOfYear(time) - 1; // // Calculate the number of days between the first day of year (1/1) and the first day of the week. // This value will be a positive value from 0 ~ 6. We call this value as "offset". // // If offset is 0, it means that the 1/1 is the start of the first week. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 12/31 1/1 1/2 1/3 1/4 1/5 1/6 // +--> First week starts here. // // If offset is 1, it means that the first day of the week is 1 day ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 // +--> First week starts here. // // If offset is 2, it means that the first day of the week is 2 days ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sat Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 1/8 // +--> First week starts here. // Day of week is 0-based. // Get the day of week for 1/1. This can be derived from the day of week of the target day. // Note that we can get a negative value. It's ok since we are going to make it a positive value when calculating the offset. int dayForJan1 = (int)gregorianCalendar.GetDayOfWeek(time) - (dayOfYear % 7); // Now, calculate the offset. Subtract the first day of week from the dayForJan1. And make it a positive value. int offset = (firstDayOfWeek - dayForJan1 + 14) % 7; if (offset != 0 && offset >= fullDays) { // If the offset is greater than the value of fullDays, it means that // the first week of the year starts on the week where Jan/1 falls on. offset -= 7; } // Calculate the day of year for specified time by taking offset into account. int day = dayOfYear - offset; if (day >= 0) { // If the day of year value is greater than zero, get the week of year. return (day / 7 + 1); } // Otherwise, the specified time falls on the week of previous year. // Call this method again by passing the last day of previous year. return GetWeekOfYearFullDays(time.AddDays(-(dayOfYear + 1)), rule, firstDayOfWeek, fullDays); }
// darws a single part of the month calendar (with one month) private void DrawSingleMonth(Graphics dc, Rectangle clip_rectangle, Rectangle rectangle, MonthCalendar mc, int row, int col) { // cache local copies of Marshal-by-ref internal members (gets around error CS0197) Size title_size = (Size)((object)mc.title_size); Size date_cell_size = (Size)((object)mc.date_cell_size); DateTime current_month = (DateTime)((object)mc.current_month); DateTime sunday = new DateTime(2006, 10, 1); // draw the title back ground DateTime this_month = current_month.AddMonths (row*mc.CalendarDimensions.Width+col); Rectangle title_rect = new Rectangle(rectangle.X, rectangle.Y, title_size.Width, title_size.Height); if (title_rect.IntersectsWith (clip_rectangle)) { dc.FillRectangle (ResPool.GetSolidBrush (mc.TitleBackColor), title_rect); // draw the title string title_text = this_month.ToString ("MMMM yyyy"); dc.DrawString (title_text, mc.bold_font, ResPool.GetSolidBrush (mc.TitleForeColor), title_rect, mc.centered_format); if (mc.ShowYearUpDown) { Rectangle year_rect; Rectangle upRect, downRect; ButtonState upState, downState; mc.GetYearNameRectangles (title_rect, row * mc.CalendarDimensions.Width + col, out year_rect, out upRect, out downRect); dc.FillRectangle (ResPool.GetSolidBrush (SystemColors.Control), year_rect); dc.DrawString (this_month.ToString ("yyyy"), mc.bold_font, ResPool.GetSolidBrush (Color.Black), year_rect, mc.centered_format); upState = mc.IsYearGoingUp ? ButtonState.Pushed : ButtonState.Normal; downState = mc.IsYearGoingDown ? ButtonState.Pushed : ButtonState.Normal; ControlPaint.DrawScrollButton (dc, upRect, ScrollButton.Up, upState); ControlPaint.DrawScrollButton (dc, downRect, ScrollButton.Down, downState); } // draw previous and next buttons if it's time if (row == 0 && col == 0) { // draw previous button DrawMonthCalendarButton ( dc, rectangle, mc, title_size, mc.button_x_offset, (System.Drawing.Size)((object)mc.button_size), true); } if (row == 0 && col == mc.CalendarDimensions.Width-1) { // draw next button DrawMonthCalendarButton ( dc, rectangle, mc, title_size, mc.button_x_offset, (System.Drawing.Size)((object)mc.button_size), false); } } // set the week offset and draw week nums if needed int col_offset = (mc.ShowWeekNumbers) ? 1 : 0; Rectangle day_name_rect = new Rectangle( rectangle.X, rectangle.Y + title_size.Height, (7 + col_offset) * date_cell_size.Width, date_cell_size.Height); if (day_name_rect.IntersectsWith (clip_rectangle)) { dc.FillRectangle (GetControlBackBrush (mc.BackColor), day_name_rect); // draw the day names DayOfWeek first_day_of_week = mc.GetDayOfWeek(mc.FirstDayOfWeek); for (int i=0; i < 7; i++) { int position = i - (int) first_day_of_week; if (position < 0) { position = 7 + position; } // draw it Rectangle day_rect = new Rectangle( day_name_rect.X + ((i + col_offset)* date_cell_size.Width), day_name_rect.Y, date_cell_size.Width, date_cell_size.Height); dc.DrawString (sunday.AddDays (i + (int) first_day_of_week).ToString ("ddd"), mc.Font, ResPool.GetSolidBrush (mc.TitleBackColor), day_rect, mc.centered_format); } // draw the vertical divider int vert_divider_y = Math.Max(title_size.Height+ date_cell_size.Height-1, 0); dc.DrawLine ( ResPool.GetPen (mc.ForeColor), rectangle.X + (col_offset * date_cell_size.Width) + mc.divider_line_offset, rectangle.Y + vert_divider_y, rectangle.Right - mc.divider_line_offset, rectangle.Y + vert_divider_y); } // draw the actual date items in the grid (including the week numbers) Rectangle date_rect = new Rectangle ( rectangle.X, rectangle.Y + title_size.Height + date_cell_size.Height, date_cell_size.Width, date_cell_size.Height); int month_row_count = 0; bool draw_week_num_divider = false; DateTime current_date = mc.GetFirstDateInMonthGrid ( new DateTime (this_month.Year, this_month.Month, 1)); for (int i=0; i < 6; i++) { // establish if this row is in our clip_area Rectangle row_rect = new Rectangle ( rectangle.X, rectangle.Y + title_size.Height + (date_cell_size.Height * (i+1)), date_cell_size.Width * 7, date_cell_size.Height); if (mc.ShowWeekNumbers) { row_rect.Width += date_cell_size.Width; } bool draw_row = row_rect.IntersectsWith (clip_rectangle); if (draw_row) { dc.FillRectangle (GetControlBackBrush (mc.BackColor), row_rect); } // establish if this is a valid week to draw if (mc.IsValidWeekToDraw (this_month, current_date, row, col)) { month_row_count = i; } // draw the week number if required if (mc.ShowWeekNumbers && month_row_count == i) { if (!draw_week_num_divider) { draw_week_num_divider = draw_row; } // get the week for this row int week = mc.GetWeekOfYear (current_date); if (draw_row) { dc.DrawString ( week.ToString(), mc.Font, ResPool.GetSolidBrush (mc.TitleBackColor), date_rect, mc.centered_format); } date_rect.Offset(date_cell_size.Width, 0); } // only draw the days if we have to if(month_row_count == i) { for (int j=0; j < 7; j++) { if (draw_row) { DrawMonthCalendarDate ( dc, date_rect, mc, current_date, this_month, row, col); } // move the day on current_date = current_date.AddDays(1); date_rect.Offset(date_cell_size.Width, 0); } // shift the rectangle down one row int offset = (mc.ShowWeekNumbers) ? -8 : -7; date_rect.Offset(offset*date_cell_size.Width, date_cell_size.Height); } } // month_row_count is zero based, so add one month_row_count++; // draw week numbers if required if (draw_week_num_divider) { col_offset = 1; dc.DrawLine ( ResPool.GetPen (mc.ForeColor), rectangle.X + date_cell_size.Width - 1, rectangle.Y + title_size.Height + date_cell_size.Height + mc.divider_line_offset, rectangle.X + date_cell_size.Width - 1, rectangle.Y + title_size.Height + date_cell_size.Height + (month_row_count * date_cell_size.Height) - mc.divider_line_offset); } }
public void DayButton_AutomationPeer() { Calendar calendar = new Calendar(); Assert.IsNotNull(calendar); _isLoaded = false; DateTime date = new DateTime(2000, 2, 2); calendar.DisplayDate = date; calendar.SelectedDate = date; CalendarAutomationPeer calendarAutomationPeer = (CalendarAutomationPeer)CalendarAutomationPeer.CreatePeerForElement(calendar); Assert.IsNotNull(calendarAutomationPeer); TestPeer testPeer = new TestPeer(calendar); calendar.Loaded += new RoutedEventHandler(calendar_Loaded); TestPanel.Children.Add(calendar); EnqueueConditional(IsLoaded); EnqueueCallback(delegate { CalendarDayButton dayButton = calendar.FindDayButtonFromDay(date); Assert.IsNotNull(dayButton); AutomationPeer peer = CalendarAutomationPeer.CreatePeerForElement(dayButton); Assert.IsNotNull(peer); Assert.AreEqual(peer.GetAutomationControlType(), AutomationControlType.Button, "Incorrect Control type for Daybutton"); Assert.AreEqual(peer.GetClassName(), dayButton.GetType().Name, "Incorrect ClassName value for DayButton"); Assert.AreEqual(peer.GetName(), dayButton.Content.ToString(), "Incorrect Name value for DayButtonPeer"); Assert.IsTrue(peer.IsContentElement(), "Incorrect IsContentElement value"); Assert.IsTrue(peer.IsControlElement(), "Incorrect IsControlElement value"); Assert.IsFalse(peer.IsKeyboardFocusable(), "Incorrect IsKeyBoardFocusable value"); #region DayButtonAutomationPeer ISelectionItemProvider tests: ISelectionItemProvider selectionItem = (ISelectionItemProvider)peer.GetPattern(PatternInterface.SelectionItem); Assert.IsNotNull(selectionItem); Assert.IsTrue(selectionItem.IsSelected); Assert.AreEqual(calendarAutomationPeer, testPeer.GetPeerFromProvider(selectionItem.SelectionContainer)); selectionItem.RemoveFromSelection(); Assert.IsFalse(selectionItem.IsSelected); selectionItem.AddToSelection(); Assert.IsTrue(selectionItem.IsSelected); //check selection in SingleDate mode CalendarDayButton dayButton2 = calendar.FindDayButtonFromDay(date.AddDays(1)); Assert.IsNotNull(dayButton2); AutomationPeer peer2 = CalendarAutomationPeer.CreatePeerForElement(dayButton2); Assert.IsNotNull(peer2); ISelectionItemProvider selectionItem2 = (ISelectionItemProvider)peer2.GetPattern(PatternInterface.SelectionItem); Assert.IsNotNull(selectionItem2); Assert.IsFalse(selectionItem2.IsSelected); selectionItem2.AddToSelection(); Assert.IsTrue(selectionItem2.IsSelected); Assert.IsFalse(selectionItem.IsSelected); //check blackout day selectionItem.RemoveFromSelection(); calendar.BlackoutDates.Add(new CalendarDateRange(date)); selectionItem.AddToSelection(); Assert.IsFalse(selectionItem.IsSelected); //check selection in None mode calendar.SelectionMode = CalendarSelectionMode.None; Assert.IsFalse(selectionItem2.IsSelected); selectionItem2.AddToSelection(); Assert.IsFalse(selectionItem2.IsSelected); //check selection in MultiRange mode calendar.BlackoutDates.Clear(); calendar.SelectionMode = CalendarSelectionMode.MultipleRange; Assert.IsFalse(selectionItem.IsSelected); Assert.IsFalse(selectionItem2.IsSelected); selectionItem.AddToSelection(); selectionItem2.AddToSelection(); Assert.IsTrue(selectionItem.IsSelected); Assert.IsTrue(selectionItem2.IsSelected); selectionItem2.RemoveFromSelection(); Assert.IsTrue(selectionItem.IsSelected); Assert.IsFalse(selectionItem2.IsSelected); #endregion #region DayButtonAutomationPeer IInvoke tests: //check selection and trailing day functionality CalendarDayButton dayButton4 = calendar.FindDayButtonFromDay(new DateTime(2000,1,31)); Assert.IsNotNull(dayButton4); AutomationPeer peer4 = CalendarAutomationPeer.CreatePeerForElement(dayButton4); Assert.IsNotNull(peer4); IInvokeProvider invokeItem = (IInvokeProvider)peer4.GetPattern(PatternInterface.Invoke); Assert.IsNotNull(invokeItem); invokeItem.Invoke(); dayButton4 = calendar.FindDayButtonFromDay(new DateTime(2000, 1, 31)); Assert.IsTrue(dayButton4.IsSelected); Assert.AreEqual(calendar.DisplayDate.Month, 1); #endregion #region DayButtonAutomationPeer ITableItemProvider tests: ITableItemProvider tableItem = (ITableItemProvider)peer.GetPattern(PatternInterface.TableItem); Assert.IsNotNull(tableItem); IRawElementProviderSimple[] headers = tableItem.GetColumnHeaderItems(); Assert.AreEqual(1, headers.Length); Assert.Equals((((ITableProvider)calendarAutomationPeer).GetColumnHeaders())[3], headers[0]); Assert.IsNull(tableItem.GetRowHeaderItems()); #endregion #region DayButtonAutomationPeer IGridItemProvider tests: foreach (UIElement child in calendar.MonthControl.MonthView.Children) { int childRow = (int)child.GetValue(Grid.RowProperty); IGridItemProvider gridItem; if (childRow != 0) { peer = CalendarDayButtonAutomationPeer.CreatePeerForElement(child); Assert.IsNotNull(peer); gridItem = (IGridItemProvider)peer.GetPattern(PatternInterface.GridItem); Assert.IsNotNull(gridItem); Assert.AreEqual(child.GetValue(Grid.ColumnProperty), gridItem.Column); Assert.AreEqual((int)child.GetValue(Grid.RowProperty) - 1, gridItem.Row); Assert.AreEqual(1, gridItem.ColumnSpan); Assert.AreEqual(1, gridItem.RowSpan); Assert.AreEqual(calendarAutomationPeer, testPeer.GetPeerFromProvider(gridItem.ContainingGrid)); } } #endregion }); EnqueueTestComplete(); }
public static DateTime GetWeekStartByDate(DateTime start) { start = start.Date; int dow = (int)start.DayOfWeek; int fdow = Mediachase.IBN.Business.PortalConfig.PortalFirstDayOfWeek; fdow = (fdow == 7) ? 0 : fdow; int diff = dow - fdow; DateTime result; if (diff < 0) result = start.AddDays(-(7 + diff)); else result = start.AddDays(-diff); if (result.Year < start.Year) result = new DateTime(start.Year, 1, 1); return result; }
public static DateTime GetFirstDateOfWeek(int year, int weekOfYear) { DateTime jan1 = new DateTime(year, 1, 1); int daysOffset = DayOfWeek.Thursday - jan1.DayOfWeek; DateTime firstThursday = jan1.AddDays(daysOffset); var cal = CultureInfo.CurrentCulture.Calendar; int firstWeek = cal.GetWeekOfYear(firstThursday, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); var weekNum = weekOfYear; if (firstWeek <= 1) { weekNum -= 1; } var result = firstThursday.AddDays(weekNum * 7); return result.AddDays(-3); }
/// <summary> /// Subtracts a time span from a date time in a global context. /// </summary> /// <param name="value">The value.</param> /// <param name="timeSpan">The time span.</param> /// <returns>The DateTime after decrementing by TimeSpan.</returns> public virtual DateTime OnDecrement(DateTime value, TimeSpan timeSpan) { // special case: value is at DateTime.MinValue if (DateTime.MinValue.Date == value.Date && value.TimeOfDay < timeSpan) { return value.AddDays(1).Subtract(timeSpan); } return value.Subtract(timeSpan); }
private CellInfo[] GetWeekDays(DateTime date) { CellInfo[] infos = new CellInfo[7]; for (int n = 0; n < infos.Length; n++) { infos[n] = GetCellInfo(date.AddDays(n)); } return infos; }
public static String GetPreviousSnap(String destRootDir, DateTime baseDate, Int32 prevLimit) { // -1���Ƃ� if (prevLimit < 1) throw new ArgumentException("�O����s���̐������s���ł�"); for (Int32 i = 0; i < prevLimit; i++) { DateTime prevDate = baseDate.AddDays(~i); String prevDir = Path.Combine(destRootDir, prevDate.ToString("yyyy") + Path.DirectorySeparatorChar + prevDate.ToString("MM") + Path.DirectorySeparatorChar + prevDate.ToString("dd")); //String prevDir = Path.Combine(destRootDir, prevDate.ToString("yyyyMMdd")); if (Directory.Exists(prevDir)) return prevDir; } return ""; }
static DateTimeModelContext() { DateTime dt = new DateTime(2014, 12, 31, 20, 12, 30, DateTimeKind.Utc); _dateTimes = Enumerable.Range(1, 5).Select(i => new DateTimeModel { Id = i, BirthdayA = dt.AddYears(i), BirthdayB = dt.AddMonths(i), BirthdayC = new List<DateTime> { dt.AddYears(i), dt.AddMonths(i), dt.AddDays(i) }, BirthdayD = new List<DateTime?> { dt.AddYears(2 * i), null, dt.AddMonths(2 * i) } }).ToList(); }