public static List<DayPunchCardUser> getStatiscNullByBetweenTime(DateTime start, DateTime end, char type, byte status) { using (DataClassesEduDataContext dc = new DataClassesEduDataContext()) { if (type == '1') { var bb = from user in dc.Users where user.UserType == '1' && !(from kq in dc.KQ_PunchCardRecords where kq.PunchCardType == type && kq.Time > start && kq.Time < end select kq.PunchCardUserId).Contains(user.Key) && !(from at in dc.KQ_Attendance where at.starttime <= start.AddHours(8) && at.endtime >= start.AddHours(8) select at.userid).Contains(user.Key) select new DayPunchCardUser { 工号 = user.JobNumber, 姓名 = user.TrueName, 电话长号 = user.changhao, 电话短号 = user.duanhao, 序号 = (user.orderNo == null) ? 0 : (int)user.orderNo }; return bb.OrderBy(a => a.序号).ToList<DayPunchCardUser>(); } if (type == '2') { var bb = from user in dc.Users where user.UserType == '1' && !(from kq in dc.KQ_PunchCardRecords where kq.PunchCardType == type && kq.Time > start && kq.Time < end select kq.PunchCardUserId).Contains(user.Key) && !(from at in dc.KQ_Attendance where at.starttime <= start.AddHours(16) && at.endtime >= start.AddHours(16) select at.userid).Contains(user.Key) select new DayPunchCardUser { 工号 = user.JobNumber, 姓名 = user.TrueName, 电话长号 = user.changhao, 电话短号 = user.duanhao, 序号 = (user.orderNo == null) ? 0 : (int)user.orderNo }; return bb.OrderBy(a => a.序号).ToList<DayPunchCardUser>(); } return null; } }
public bool CheckPostponeIsPossible(int performanceId, DateTime date, int venueId) { IPerformanceDao dao = DALFactory.CreatePerformanceDao(database); IVenueDao venueDao = DALFactory.CreateVenueDao(database); Performance toPostpone = dao.findById(performanceId); IList<Performance> otherPerformances = dao.FindPerormanceByDay(date); bool foundConflict = false; foreach(Performance p in otherPerformances) { if(p.Id == toPostpone.Id) { continue; } DateTime postPoneDate = new DateTime(date.Year, date.Month, date.Day, date.Hour, 0, 0); DateTime currentDate = new DateTime(p.StagingTime.Year, p.StagingTime.Month, p.StagingTime.Day, p.StagingTime.Hour, 0, 0); if (toPostpone.Artist.Id == p.Artist.Id) { if(postPoneDate >= currentDate.AddHours(-2) && postPoneDate <= currentDate.AddHours(2)) { foundConflict = true; break; } } if(p.Venue.Id == venueId && postPoneDate == currentDate) { foundConflict = true; break; } } return !foundConflict; }
public void NoOverlappingIndentifierShouldPass() { // Assert var start = new DateTime(1999, 1, 1); var finish = new DateTime(2020, 12, 31); var validity = new DateRange(start, finish); var system = new SourceSystem { Name = "Test" }; var expectedPartyRole = new PartyRole() { PartyRoleType = "PartyRole" }; var expected = new PartyRoleMapping { System = system, MappingValue = "1", Validity = validity, PartyRole = expectedPartyRole }; var list = new List<PartyRoleMapping> { expected }; var repository = new Mock<IRepository>(); repository.Setup(x => x.Queryable<PartyRoleMapping>()).Returns(list.AsQueryable()); repository.Setup(x => x.FindOne<PartyRole>(It.IsAny<int>())).Returns(expectedPartyRole); var identifier = new EnergyTrading.Mdm.Contracts.MdmId { SystemName = "Test", Identifier = "1", StartDate = start.AddHours(-10), EndDate = start.AddHours(-5) }; var request = new CreateMappingRequest() { EntityId = 1, Mapping = identifier }; var rule = new PartyRoleCreateMappingdNoOverlappingRule<PartyRole, PartyRoleMapping>(repository.Object); // Act var result = rule.IsValid(request); // Assert repository.Verify(x => x.FindOne<PartyRole>(It.IsAny<int>())); Assert.IsTrue(result, "Rule failed"); }
/// <summary> /// Resets the activation timer to fire when the next future revision of any document needs to become current. /// </summary> /// <remarks> /// This is called any time a new revision is stored, preventing us from having to poll periodically. /// </remarks> internal void ResetTimer(DateTime runDate, DateTime now) { // Don't wait at all if we were asked to wait forever. if (runDate == DateTime.MaxValue) return; // Never wait more than an hour from now. Running early is ok. if (runDate > now.AddHours(1)) runDate = now.AddHours(1); // If rundate as passed, use now. if (runDate < now) runDate = now; // If the rundate is later than we're already waiting, then ignore it. if (runDate >= _nextRunDate) return; // Hold on to the date for comparison next time around _nextRunDate = runDate; // Determine the wait time var wait = (long) (runDate - now).TotalMilliseconds; if (wait < 0) wait = 0; // Set the timer. _timer.Change(wait, -1); }
public void OverlappingIdentifierFails() { // Assert var start = new DateTime(1999, 1, 1); var finish = new DateTime(2020, 12, 31); var validity = new DateRange(start, finish); var system = new SourceSystem { Name = "Test" }; var expected = new SourceSystemMapping { System = system, MappingValue = "1", Validity = validity }; var list = new System.Collections.Generic.List<SourceSystemMapping> { expected }; var repository = new Mock<IRepository>(); repository.Setup(x => x.Queryable<SourceSystemMapping>()).Returns(list.AsQueryable()); var identifier = new EnergyTrading.Mdm.Contracts.MdmId { SystemName = "Test", Identifier = "1", StartDate = start.AddHours(5), EndDate = start.AddHours(10) }; var request = new AmendMappingRequest() { EntityId = 1, Mapping = identifier, MappingId = 1 }; var rule = new AmendMappingNoOverlappingRule<SourceSystemMapping>(repository.Object); // Act var result = rule.IsValid(request); // Assert repository.Verify(x => x.Queryable<SourceSystemMapping>()); Assert.IsFalse(result, "Rule failed"); }
//===================================================================== /// <summary> /// This loads the time zone information from the registry when the form is loaded and sets the form /// defaults. /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void EventRecurTestForm_Load(object sender, EventArgs e) { TimeZoneRegInfo.LoadTimeZoneInfo(); // Load the time zone combo box. The first entry will be for no time zone. cboTimeZone.Items.Add("No time zone"); foreach(VTimeZone vtz in VCalendar.TimeZones) cboTimeZone.Items.Add(vtz.TimeZoneId.Value); cboTimeZone.SelectedIndex = 0; DateTime dtDate = new DateTime(DateTime.Today.Year, 1, 1); dtpStartDate.Value = dtDate; dtpEndDate.Value = dtDate.AddMonths(3); txtCalendar.Text = String.Format( "BEGIN:VEVENT\r\n" + "DTSTART:{0}\r\n" + "DTEND:{1}\r\n" + "RRULE:FREQ=DAILY;COUNT=10;INTERVAL=5\r\n" + "END:VEVENT\r\n", dtDate.AddHours(9).ToUniversalTime().ToString(ISO8601Format.BasicDateTimeUniversal), dtDate.AddHours(10).ToUniversalTime().ToString(ISO8601Format.BasicDateTimeUniversal)); }
public IHttpActionResult GetResult(DateTime date, int hour, string name, string eNodebName, byte sectorId) { CollegeInfo college = _collegeRepository.FirstOrDefault(x => x.Name == name); if (college == null) return BadRequest("Bad College Name!"); ENodeb eNodeb = _eNodebRepository.FirstOrDefault(x => x.Name == eNodebName); if (eNodeb == null) return BadRequest("Bad ENodeb Name!"); DateTime time = date.AddHours(hour); College4GTestResults result = _repository.FirstOrDefault( x => x.TestTime == time && x.CollegeId == college.Id); if (result == null) return Ok(new College4GTestResults { TestTime = date.AddHours(hour), CollegeId = college.Id, ENodebId = eNodeb.ENodebId, AccessUsers = 20, DownloadRate = 8000, UploadRate = 3000, SectorId = sectorId, Rsrp = -90, Sinr = 14 }); result.ENodebId = eNodeb.ENodebId; result.SectorId = sectorId; return Ok(result); }
public override DateTime Next(DateTime time, out bool changed) { changed = false; if (Values.Count < 1) { return time; } if (Type == CGtd.DATES_TYPE_EACH) { return time.AddHours(Values[0]); } if (Type == CGtd.DATES_TYPE_WHEN) { int idx = time.Hour; int tmp = NextValue(idx, changed); if (tmp > 0) { return time.AddHours(tmp); } if (tmp < 0) { changed = true; return time.AddDays(1).AddHours(Values[0] - idx); } } return time; }
private System.DateTime getDeliveryDateTime(string serviceCode, System.DateTime deliveryDate) { System.DateTime result = deliveryDate; switch (serviceCode) { case "PRIORITYOVERNIGHT": result = result.AddHours(10.5); break; case "FIRSTOVERNIGHT": result = result.AddHours(8.5); break; case "STANDARDOVERNIGHT": result = result.AddHours(15); break; case "FEDEX2DAY": case "FEDEXEXPRESSSAVER": result = result.AddHours(16.5); break; default: // no specific time, so use 11:59 PM to ensure correct sorting result = result.AddHours(23).AddMinutes(59); break; } return(result); }
public void Setup() { now = DateTime.Now; inOneHour = now.AddHours(1); inTwoHours = now.AddHours(2); inThreeHours = now.AddHours(3); }
public void GivenAnOwnerAndRepoAndEmailWhenGettingTheLastCommit() { _owner = "my owner"; _repo = "my repo"; _userEmail = "email1"; _expectedResource = string.Format("/repos/{0}/{1}", _owner, _repo); _commitDate = DateTime.UtcNow; _returnedCommits = new List<RepoCommit> { new RepoCommit { Commit = new Commit { CommitCommitter = new CommitCommitter { Email = _userEmail, Date = _commitDate.AddHours(-1) } } }, new RepoCommit { Commit = new Commit { CommitCommitter = new CommitCommitter { Email = "email2", Date = _commitDate.AddHours(1) } } }, new RepoCommit { Commit = new Commit { CommitCommitter = new CommitCommitter { Email = _userEmail, Date = _commitDate } } } }; var mockRestResponse = new Mock<IRestResponse<List<RepoCommit>>>(); mockRestResponse .SetupGet(response => response.Data) .Returns(_returnedCommits); _mockRestClient = new Mock<IRestClient>(); _mockRestClient .Setup(client => client.Execute<List<RepoCommit>>(It.IsAny<IRestRequest>())) .Returns(mockRestResponse.Object); ; var service = new RepoCommittersService(_mockRestClient.Object); _repoCommit = service.GetCommitterLastCommit(_owner, _repo, _userEmail); }
public void NoFilterTest() { DateTime date1 = new DateTime( 2011, 4, 12 ); CalendarDateDiff calendarDateDiff = new CalendarDateDiff(); Assert.AreEqual( calendarDateDiff.Difference( date1, date1.AddHours( 1 ) ), new TimeSpan( 1, 0, 0 ) ); Assert.AreEqual( calendarDateDiff.Difference( date1, date1.AddHours( -1 ) ), new TimeSpan( -1, 0, 0 ) ); }
private static DateTime ParseRFC822DateNow(string dateString, DateTime defaultDate) { bool bolSuccess = false; System.DateTime dteParsedDate = default(System.DateTime); int intLastSpaceIndex = dateString.LastIndexOf(" "); // First, try to parse the date with .NET's engine try { // Parse date dteParsedDate = System.DateTime.Parse(dateString, DateTimeFormatInfo.InvariantInfo); // Set to UTC if GMT or Z timezone info is given if (dateString.Substring(intLastSpaceIndex + 1) == "GMT" | dateString.Substring(intLastSpaceIndex + 1) == "Z") { dteParsedDate.ToUniversalTime(); } bolSuccess = true; } catch (Exception) { // Parsing failed, mark to try it "by hand" bolSuccess = false; } if (!bolSuccess) { // Try a manual parse now without timezone information string strTimezone = dateString.Substring(intLastSpaceIndex + 1); string strReducedDate = dateString.Substring(0, intLastSpaceIndex); dteParsedDate = System.DateTime.Parse(strReducedDate, DateTimeFormatInfo.InvariantInfo); // Now, calculate UTC based on the given timezone in the date string if (strTimezone.StartsWith("+")) { // The Timezone is given as a +hhmm string dteParsedDate.AddHours(-int.Parse(strReducedDate.Substring(1, 2))); dteParsedDate.AddMinutes(-int.Parse(strReducedDate.Substring(3))); } else if (strTimezone.StartsWith("-")) { // The Timezone is given as a -hhmm string // The Timezone is given as a +hhmm string dteParsedDate.AddHours(int.Parse(strReducedDate.Substring(1, 2))); dteParsedDate.AddMinutes(int.Parse(strReducedDate.Substring(3))); } else { // The Timezone is given as a named string dteParsedDate = dteParsedDate.AddHours(GetHoursByCode(strTimezone)); } } return(dteParsedDate); }
/// <summary> Limit a date's resolution. For example, the date <code>1095767411000</code> /// (which represents 2004-09-21 13:50:11) will be changed to /// <code>1093989600000</code> (2004-09-01 00:00:00) when using /// <code>Resolution.MONTH</code>. /// /// </summary> /// <param name="resolution">The desired resolution of the date to be returned /// </param> /// <returns> the date with all values more precise than <code>resolution</code> /// set to 0 or 1, expressed as milliseconds since January 1, 1970, 00:00:00 GMT /// </returns> public static long Round(long time, Resolution resolution) { System.Globalization.Calendar cal = new System.Globalization.GregorianCalendar(); // {{Aroush}} do we care about 'cal' // protected in JDK's prior to 1.4 //cal.setTimeInMillis(time); System.DateTime dt = new System.DateTime(time); if (resolution == Resolution.YEAR) { dt = dt.AddMonths(1 - dt.Month); dt = dt.AddDays(1 - dt.Day); dt = dt.AddHours(0 - dt.Hour); dt = dt.AddMinutes(0 - dt.Minute); dt = dt.AddSeconds(0 - dt.Second); dt = dt.AddMilliseconds(0 - dt.Millisecond); } else if (resolution == Resolution.MONTH) { dt = dt.AddDays(1 - dt.Day); dt = dt.AddHours(0 - dt.Hour); dt = dt.AddMinutes(0 - dt.Minute); dt = dt.AddSeconds(0 - dt.Second); dt = dt.AddMilliseconds(0 - dt.Millisecond); } else if (resolution == Resolution.DAY) { dt = dt.AddHours(0 - dt.Hour); dt = dt.AddMinutes(0 - dt.Minute); dt = dt.AddSeconds(0 - dt.Second); dt = dt.AddMilliseconds(0 - dt.Millisecond); } else if (resolution == Resolution.HOUR) { dt = dt.AddMinutes(0 - dt.Minute); dt = dt.AddSeconds(0 - dt.Second); dt = dt.AddMilliseconds(0 - dt.Millisecond); } else if (resolution == Resolution.MINUTE) { dt = dt.AddSeconds(0 - dt.Second); dt = dt.AddMilliseconds(0 - dt.Millisecond); } else if (resolution == Resolution.SECOND) { dt = dt.AddMilliseconds(0 - dt.Millisecond); } else if (resolution == Resolution.MILLISECOND) { // don't cut off anything } else { throw new System.ArgumentException("unknown resolution " + resolution); } return(dt.Ticks); }
public void StartNewDay(int _numProblems, int _hoursInDay) { SpawningTimes.Clear(); System.DateTime currentTime = timerManager.GetTime(); int hoursInFirstDay = _hoursInDay; ProblemsToSpawn = _numProblems; float timeBetweenProblems = (float)hoursInFirstDay / (float)ProblemsToSpawn; int problemsPerCategory = ProblemsToSpawn / 4; Dictionary <IssueType, int> numCategorySpawned = new Dictionary <IssueType, int>(); numCategorySpawned.Add(IssueType.AnimalControl, 0); numCategorySpawned.Add(IssueType.Environment, 0); numCategorySpawned.Add(IssueType.Infrastructure, 0); numCategorySpawned.Add(IssueType.Regulations, 0); int randomCategory = 0; int categoryWhileCheck = 0; for (int i = 0; i < (problemsPerCategory * 4); ++i) { randomCategory = Random.Range(0, 4); while (numCategorySpawned[(IssueType)randomCategory] >= problemsPerCategory) { categoryWhileCheck++; randomCategory++; if (randomCategory == 4) { randomCategory = 0; } if (categoryWhileCheck > 4) { Debug.Log("This shouldn't be happening"); break; } } SpawningTimes.Add(new IssueTime((IssueType)randomCategory, currentTime)); numCategorySpawned[(IssueType)randomCategory] += 1; currentTime = currentTime.AddHours(timeBetweenProblems); categoryWhileCheck = 0; } int checkEven = problemsPerCategory * 4; while (checkEven < ProblemsToSpawn) { randomCategory = Random.Range(0, 4); SpawningTimes.Add(new IssueTime((IssueType)randomCategory, currentTime)); numCategorySpawned[(IssueType)randomCategory] += 1; currentTime = currentTime.AddHours(timeBetweenProblems); checkEven++; } }
// parse "last minute", "next hour" private DateTimeResolutionResult ParseRelativeUnit(string text, DateObject referenceTime) { var ret = new DateTimeResolutionResult(); var match = Config.RelativeTimeUnitRegex.Match(text); if (match.Success) { var srcUnit = match.Groups["unit"].Value.ToLower(); var unitStr = Config.UnitMap[srcUnit]; int swiftValue = 1; var prefixMatch = Config.PastRegex.Match(text); if (prefixMatch.Success) { swiftValue = -1; } DateObject beginTime; var endTime = beginTime = referenceTime; if (Config.UnitMap.ContainsKey(srcUnit)) { switch (unitStr) { case "H": beginTime = swiftValue > 0 ? beginTime : referenceTime.AddHours(swiftValue); endTime = swiftValue > 0 ? referenceTime.AddHours(swiftValue) : endTime; break; case "M": beginTime = swiftValue > 0 ? beginTime : referenceTime.AddMinutes(swiftValue); endTime = swiftValue > 0 ? referenceTime.AddMinutes(swiftValue) : endTime; break; case "S": beginTime = swiftValue > 0 ? beginTime : referenceTime.AddSeconds(swiftValue); endTime = swiftValue > 0 ? referenceTime.AddSeconds(swiftValue) : endTime; break; default: return(ret); } ret.Timex = $"({FormatUtil.LuisDate(beginTime)}T{FormatUtil.LuisTime(beginTime)},{FormatUtil.LuisDate(endTime)}T{FormatUtil.LuisTime(endTime)},PT1{unitStr[0]})"; ret.FutureValue = ret.PastValue = new Tuple <DateObject, DateObject>(beginTime, endTime); ret.Success = true; return(ret); } } return(ret); }
public void Test_ExitVehicle_AlreadyExited_ShouldReturnErrorMessage() { var park = new VehiclePark(1, 2); var car = new Car("CA1011AH", "John Smith", 1); DateTime insertDate = new DateTime(2015, 5, 10, 10, 0, 0); park.InsertCar(car, 1, 1, insertDate); park.ExitVehicle("CA1011AH", insertDate.AddHours(2), 10.0M); string message = park.ExitVehicle("CA1011AH", insertDate.AddHours(2), 10.0M); Assert.AreEqual("There is no vehicle with license plate CA1011AH in the park", message); }
/// <summary> /// Function that averages a series based on a defined Time-Interval /// </summary> /// <param name="s">Input Series</param> /// <param name="tInterval">Averaging Time-Interval</param> /// <returns></returns> public static Series Average(Series s, TimeInterval tInterval) { Series rval = s.Clone(); if (s.Count == 0) return rval; // Define starting date of averaging process DateTime t = new DateTime(s[0].DateTime.Year, s[0].DateTime.Month, s[0].DateTime.Day, s[0].DateTime.Hour, 0, 0); // Find which averaging process to accomplish if (tInterval == TimeInterval.Daily) { // Define series time-interval rval.TimeInterval = TimeInterval.Daily; // Loop through the dates while (t < s[s.Count - 1].DateTime.Date) { // Get the series subset based on the averaging time-interval Series sTemp = s.Subset(t, t.AddDays(1)); // Average the values of the subset DoAverage(rval, t, sTemp); // Increment DateTime by averaging time-interval t = t.AddDays(1); } } // Ditto on the other processes below else if (tInterval == TimeInterval.Monthly) { rval.TimeInterval = TimeInterval.Monthly; while (t < s[s.Count - 1].DateTime.Date) { Series sTemp = s.Subset(t, t.AddMonths(1)); DoAverage(rval, t, sTemp); t = t.AddMonths(1); } } else if (tInterval == TimeInterval.Hourly) { rval.TimeInterval = TimeInterval.Hourly; while (t < s.MaxDateTime) { Series sTemp = Math.Subset(s, new DateRange(t, t.AddHours(1)), false); DoAverage(rval, t, sTemp); t = t.AddHours(1); } } else { throw new Exception("Time Interval " + tInterval.ToString() + " not supported!"); } return rval; }
static void Run() { // ExStart: PagingSupportForListingAppointments using (IEWSClient client = EWSClient.GetEWSClient("exchange.domain.com", "username", "password")) { try { Appointment[] appts = client.ListAppointments(); Console.WriteLine(appts.Length); DateTime date = DateTime.Now; DateTime startTime = new DateTime(date.Year, date.Month, date.Day, date.Hour, 0, 0); DateTime endTime = startTime.AddHours(1); int appNumber = 10; Dictionary<string, Appointment> appointmentsDict = new Dictionary<string, Appointment>(); for (int i = 0; i < appNumber; i++) { startTime = startTime.AddHours(1); endTime = endTime.AddHours(1); string timeZone = "America/New_York"; Appointment appointment = new Appointment( "Room 112", startTime, endTime, "*****@*****.**", "*****@*****.**"); appointment.SetTimeZone(timeZone); appointment.Summary = "NETWORKNET-35157_3 - " + Guid.NewGuid().ToString(); appointment.Description = "EMAILNET-35157 Move paging parameters to separate class"; string uid = client.CreateAppointment(appointment); appointmentsDict.Add(uid, appointment); } AppointmentCollection totalAppointmentCol = client.ListAppointments(); ///// LISTING APPOINTMENTS WITH PAGING SUPPORT /////// int itemsPerPage = 2; List<AppointmentPageInfo> pages = new List<AppointmentPageInfo>(); AppointmentPageInfo pagedAppointmentCol = client.ListAppointmentsByPage(itemsPerPage); Console.WriteLine(pagedAppointmentCol.Items.Count); pages.Add(pagedAppointmentCol); while (!pagedAppointmentCol.LastPage) { pagedAppointmentCol = client.ListAppointmentsByPage(itemsPerPage, pagedAppointmentCol.PageOffset + 1); pages.Add(pagedAppointmentCol); } int retrievedItems = 0; foreach (AppointmentPageInfo folderCol in pages) retrievedItems += folderCol.Items.Count; } finally { } } // ExEnd: PagingSupportForListingAppointments }
public void wczytajKalendarz() { DateTime login = new DateTime(2010,12,1,9,0,0); DzienOB d1 = new DzienOB(new DateTime(2010,12,1), login,login.AddHours(8),TimeSpan.FromHours(8),TypDnia.Praca); DzienOB d2 = new DzienOB(new DateTime(2010,12,2), login,login.AddHours(8),TimeSpan.FromHours(8),TypDnia.Praca); DzienOB d3 = new DzienOB(new DateTime(2010,12,3), login,login.AddHours(8),TimeSpan.FromHours(8),TypDnia.Praca); DzienOB d4 = new DzienOB(new DateTime(2010,12,4), DateTime.MinValue,DateTime.MinValue,TimeSpan.FromHours(8),TypDnia.DoOdrobienia); DzienOB d5 = new DzienOB(new DateTime(2010,12,5), DateTime.MinValue, DateTime.MinValue, TimeSpan.FromHours(0), TypDnia.Wolne); DzienOB d6 = new DzienOB(new DateTime(2010,12,6), login,login.AddHours(8),TimeSpan.FromHours(8),TypDnia.Praca); DzienOB d7 = new DzienOB(new DateTime(2010,12,7), DateTime.MinValue,DateTime.MinValue,TimeSpan.FromHours(0),TypDnia.Wolne); kalendarz.dodaj(d1).dodaj(d2).dodaj(d3).dodaj(d4).dodaj(d5).dodaj(d6).dodaj(d7); }
/// <summary> /// Converts the String to a DateTime equivalent using the specified time zone /// </summary> /// <param name="s"></param> /// <param name="timeZone"></param> /// <param name="dateTimeKind"></param> /// <returns></returns> public static DateTime ToDateTime(string s, TzTimeZone timeZone, DateTimeKind dateTimeKind) { if (string.IsNullOrEmpty(s)) throw new ArgumentException(nameof(s)); if (timeZone == null) throw new ArgumentNullException(nameof(timeZone)); if (dateTimeKind == DateTimeKind.Unspecified) throw new ArgumentException(nameof(dateTimeKind)); System.Text.RegularExpressions.Match m = dateRegex.Match(s); if (m.Success) { DateTime result = new DateTime(Convert.ToInt32(m.Groups["YEAR"].Value), Convert.ToInt32(m.Groups["MONTH"].Value), Convert.ToInt32(m.Groups["DAY"].Value), Convert.ToInt32(m.Groups["HOUR"].Value), Convert.ToInt32(m.Groups["MINUTE"].Value), Convert.ToInt32(m.Groups["SEC"].Value), DateTimeKind.Local); if (m.Groups["MS"].Success) { result = result.AddMilliseconds(Convert.ToInt32(m.Groups["MS"])); } // Date is local, check return if (m.Groups["UTC"].Success) { if (dateTimeKind == DateTimeKind.Utc) return DateTime.SpecifyKind(result, DateTimeKind.Utc); else return timeZone.ToLocalTime(DateTime.SpecifyKind(result, DateTimeKind.Utc)); } else { // Date string is local, check offset if (m.Groups["SGN"].Success) { // Translate in utc if (m.Groups["SGN"].Value == "+") result = result.AddHours(-Convert.ToInt32(m.Groups["SH"].Value)).AddMinutes(-Convert.ToInt32(m.Groups["SM"].Value)); else result = result.AddHours(Convert.ToInt32(m.Groups["SH"].Value)).AddMinutes(Convert.ToInt32(m.Groups["SM"].Value)); if (dateTimeKind == DateTimeKind.Utc) return DateTime.SpecifyKind(result, DateTimeKind.Utc); else return timeZone.ToLocalTime(DateTime.SpecifyKind(result, DateTimeKind.Utc)); } else { // Zone unspecified, suppose to be local if (dateTimeKind == DateTimeKind.Utc) return timeZone.ToUniversalTime(result); else return result; } } } throw new ArgumentException(string.Format("{0} is not a valid format", s)); }
/// <summary> Limit a date's resolution. For example, the date <c>1095767411000</c> /// (which represents 2004-09-21 13:50:11) will be changed to /// <c>1093989600000</c> (2004-09-01 00:00:00) when using /// <c>Resolution.MONTH</c>. /// /// </summary> /// <param name="time">The time in milliseconds (not ticks).</param> /// <param name="resolution">The desired resolution of the date to be returned /// </param> /// <returns> the date with all values more precise than <c>resolution</c> /// set to 0 or 1, expressed as milliseconds since January 1, 1970, 00:00:00 GMT /// </returns> public static long Round(long time, Resolution resolution) { var dt = new System.DateTime(time * TimeSpan.TicksPerMillisecond); if (resolution == Resolution.YEAR) { dt = dt.AddMonths(1 - dt.Month); dt = dt.AddDays(1 - dt.Day); dt = dt.AddHours(0 - dt.Hour); dt = dt.AddMinutes(0 - dt.Minute); dt = dt.AddSeconds(0 - dt.Second); dt = dt.AddMilliseconds(0 - dt.Millisecond); } else if (resolution == Resolution.MONTH) { dt = dt.AddDays(1 - dt.Day); dt = dt.AddHours(0 - dt.Hour); dt = dt.AddMinutes(0 - dt.Minute); dt = dt.AddSeconds(0 - dt.Second); dt = dt.AddMilliseconds(0 - dt.Millisecond); } else if (resolution == Resolution.DAY) { dt = dt.AddHours(0 - dt.Hour); dt = dt.AddMinutes(0 - dt.Minute); dt = dt.AddSeconds(0 - dt.Second); dt = dt.AddMilliseconds(0 - dt.Millisecond); } else if (resolution == Resolution.HOUR) { dt = dt.AddMinutes(0 - dt.Minute); dt = dt.AddSeconds(0 - dt.Second); dt = dt.AddMilliseconds(0 - dt.Millisecond); } else if (resolution == Resolution.MINUTE) { dt = dt.AddSeconds(0 - dt.Second); dt = dt.AddMilliseconds(0 - dt.Millisecond); } else if (resolution == Resolution.SECOND) { dt = dt.AddMilliseconds(0 - dt.Millisecond); } else if (resolution == Resolution.MILLISECOND) { // don't cut off anything } else { throw new System.ArgumentException("unknown resolution " + resolution); } return(dt.Ticks); }
private DateTimeResolutionResult ParseDateWithPeriodPrefix(string text, DateObject referenceTime) { var ret = new DateTimeResolutionResult(); var dateResult = this.Config.DateExtractor.Extract(text); if (dateResult.Count > 0) { var beforeString = text.Substring(0, (int)dateResult.Last().Start).TrimEnd(); var match = Config.PrefixDayRegex.Match(beforeString); if (match.Success) { var pr = this.Config.DateParser.Parse(dateResult.Last(), referenceTime); if (pr.Value != null) { var startTime = (DateObject)((DateTimeResolutionResult)pr.Value).FutureValue; startTime = new DateObject(startTime.Year, startTime.Month, startTime.Day); var endTime = startTime; if (match.Groups["EarlyPrefix"].Success) { endTime = endTime.AddHours(Constants.HalfDayHourCount); ret.Mod = Constants.EARLY_MOD; } else if (match.Groups["MidPrefix"].Success) { startTime = startTime.AddHours(Constants.HalfDayHourCount - Constants.HalfMidDayDurationHourCount); endTime = endTime.AddHours(Constants.HalfDayHourCount + Constants.HalfMidDayDurationHourCount); ret.Mod = Constants.MID_MOD; } else if (match.Groups["LatePrefix"].Success) { startTime = startTime.AddHours(Constants.HalfDayHourCount); endTime = startTime.AddHours(Constants.HalfDayHourCount); ret.Mod = Constants.LATE_MOD; } else { return(ret); } ret.Timex = pr.TimexStr; ret.PastValue = ret.FutureValue = new Tuple <DateObject, DateObject>(startTime, endTime); ret.Success = true; } } } return(ret); }
/// <summary> /// Initializes a new instance of the <see cref="Session" /> class. /// </summary> /// <param name="sessionType">Type of the session.</param> /// <param name="talks">The talks.</param> /// <param name="date">The date.</param> public Session(SessionTypes sessionType, List<ITalk> talks, DateTime date) { //Use only date component and excluded time. date = date.Date; SessionType = sessionType; NextTalkStartTime = date; NextTalkStartTime = (sessionType == SessionTypes.Morning) ? NextTalkStartTime.AddHours(9) //Morning session starts @ 09:00 AM : NextTalkStartTime.AddHours(13); //Afternoon session starts @ 01:00 PM BufferDuration = (sessionType == SessionTypes.Morning) ? 0 : Constants.DefaultBufferTime; Talks = talks; }
public static DateTime RetrieveLinkerTimestamp(Type appType) { // See: http://social.msdn.microsoft.com/Forums/en-BZ/winappswithcsharp/thread/012db5c6-a811-48a9-8d27-9a21878263b4 //Assembly assembly = appType.GetTypeInfo().Assembly; //var version = assembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute)) as AssemblyFileVersionAttribute; Assembly assembly = appType.GetTypeInfo().Assembly; var assemblyName = new AssemblyName(assembly.FullName); DateTime buildDate = new DateTime(2000, 1, 1).AddDays(assemblyName.Version.Build).AddSeconds(assemblyName.Version.Revision * 2); return TimeZoneInfo.Local.IsDaylightSavingTime(buildDate) ? buildDate.AddHours(TimeZoneInfo.Local.BaseUtcOffset.Hours) : buildDate.AddHours(TimeZoneInfo.Local.BaseUtcOffset.Hours - 1); }
private void SimulateCustomerActivityFor3rdJune() { // quiet normal day var startOfDay = new DateTime(2014, 06, 03); account1.TopUp(new Money(5), TestClock(startOfDay.AddHours(10))); account1.Record(PhoneCall(startOfDay.AddHours(10.5), 5), Cost(), null); account1.Record(PhoneCall(startOfDay.AddHours(20), 10), Cost(), null); account4.TopUp(new Money(10), TestClock(startOfDay.AddHours(18))); account4.Record(PhoneCall(startOfDay.AddHours(18.1), 7), Cost(), null); }
public static DateTime ArrumarFusoHorario(DateTime data, FusoHorario.FusoHorario fusoHorario) { DateTime dataAlterada; try { int dataIni = DateTime.Compare(data, fusoHorario.InicioHorarioVerao); int dataFim = DateTime.Compare(data, fusoHorario.FinalHorarioVerao); if (dataIni >= 0 && dataFim <= 0) { if (fusoHorario.ControlaHorarioVerao) dataAlterada = data.AddHours(fusoHorario.FusoHorarioVerao); else dataAlterada = data.AddHours(fusoHorario.FusoHorarioAtual); } else dataAlterada = data.AddHours(fusoHorario.FusoHorarioAtual); } catch (Exception ex) { throw new Exception("Não foi possível converter a data para o fuso correto. Erro: " + ex.Message); } //DateTime dataAlterada; //try //{ // int dataIni = DateTime.Compare(data, fusoHorario.InicioHorarioVerao); // int dataFim = DateTime.Compare(data, fusoHorario.FinalHorarioVerao); // if (dataIni >= 0 && dataFim <= 0) // { // if (fusoHorario.ControlaHorarioVerao) // dataAlterada = new DateTime(data.Year, data.Month, ArrumarDia(data.Day, data.Hour, fusoHorario.FusoHorarioVerao), ArrumarHora(data.Hour, fusoHorario.FusoHorarioVerao), data.Minute, data.Second, data.Kind); // else // dataAlterada = new DateTime(data.Year, data.Month, ArrumarDia(data.Day, data.Hour, fusoHorario.FusoHorarioAtual), ArrumarHora(data.Hour, fusoHorario.FusoHorarioAtual), data.Minute, data.Second, data.Kind); // } // else // dataAlterada = new DateTime(data.Year, data.Month, ArrumarDia(data.Day, data.Hour, fusoHorario.FusoHorarioAtual), ArrumarHora(data.Hour, fusoHorario.FusoHorarioAtual), data.Minute, data.Second, data.Kind); //} //catch (Exception ex) //{ // throw new Exception("Não foi possível converter a data para o fuso correto. Erro: " + ex.Message); //} return dataAlterada; }
public static bool TryAppendTimeHMS(DateTime date, string input, DateTime defaultDate, out DateTime dateOutput) { if (string.IsNullOrEmpty(input)) { dateOutput = defaultDate; return false; } input = input.Trim(); if (input.Length == 0) { dateOutput = defaultDate; return false; } try { switch (input.Length) { case 1: case 2: dateOutput = date.AddHours(int.Parse(input)); return true; case 3: dateOutput = date.AddHours(int.Parse(input.Substring(0, 2))); dateOutput = dateOutput.AddMinutes(int.Parse(input.Substring(2, 1))); return true; case 4: dateOutput = date.AddHours(int.Parse(input.Substring(0, 2))); dateOutput = dateOutput.AddMinutes(int.Parse(input.Substring(2, 2))); return true; case 5: dateOutput = date.AddHours(int.Parse(input.Substring(0, 2))); dateOutput = dateOutput.AddMinutes(int.Parse(input.Substring(2, 2))); dateOutput = dateOutput.AddSeconds(int.Parse(input.Substring(4, 1))); return true; default: dateOutput = date.AddHours(int.Parse(input.Substring(0, 2))); dateOutput = dateOutput.AddMinutes(int.Parse(input.Substring(2, 2))); dateOutput = dateOutput.AddSeconds(int.Parse(input.Substring(4, 2))); return true; } } catch { dateOutput = defaultDate; return false; } }
/// <summary> /// Decodes day string to DatetTime /// </summary> /// <param name="today"></param> /// <param name="dayDescription"></param> /// <returns></returns> public static DateTime GetDay(DateTime today, string dayDescription) { DateTime day = new DateTime(today.Year, today.Month, today.Day,0,0,0); string numericTime = dayDescription.Replace("am", "").Replace("pm", "").Trim(); day = day.AddHours(Convert.ToInt32(numericTime.Split(':')[0])); day = day.AddMinutes(Convert.ToInt32(numericTime.Split(':')[1])); if (dayDescription.Contains("pm")) { day = day.AddHours(12); } return day; }
public void Between() { var date = new DateTime(2015, 8, 7, 13, 26, 30); Assert.IsTrue(date.Between(date.AddMonths(-3), date.AddMonths(3))); Assert.IsTrue(date.AddHours(36).Between(date.AddMonths(-3), date.AddMonths(3))); Assert.IsFalse(date.AddMonths(6).Between(date.AddMonths(-3), date.AddMonths(3))); Assert.IsFalse(date.AddHours(-2).Between(date, date.AddMonths(3))); Assert.IsTrue(date.Between(date.AddMonths(-3), date.AddMonths(3), false)); Assert.IsTrue(date.AddHours(36).Between(date.AddMonths(-3), date.AddMonths(3), false)); Assert.IsFalse(date.AddMonths(6).Between(date.AddMonths(-3), date.AddMonths(3), false)); Assert.IsTrue(date.AddHours(-2).Between(date, date.AddMonths(3), false)); Assert.IsFalse(date.AddHours(-24).Between(date, date.AddMonths(3), false)); }
public void Should_be_able_to_satisfy_a_stepped_values() { var field = new CronHour("5-10/5"); var control = new DateTime(2011, 01, 01, 0, 0, 0); var date = field.SnapForward(control); Assert.AreEqual(control.AddHours(5), date); date = field.SnapForward(date.AddHours(1)); Assert.AreEqual(control.AddHours(10), date); date = field.SnapForward(date.AddHours(1)); Assert.AreEqual(control.AddHours(29), date); }
private static void Immutiable() { string name = " Scott "; name.Trim(); Console.WriteLine(name); //above will not modify the name, so to fix it we have to do name = name.Trim(); DateTime date = new DateTime(2014, 1, 1); date.AddHours(25); Console.WriteLine(date); //above will not modify the date time because its immutiuble // its constructing the new date for me date = date.AddHours(25); }
private bool CheckTime(List<Order> AlreadyBooked, DateTime _TimeDate, int AddHour) { bool _check = true; foreach (Order checking in AlreadyBooked) { if (_TimeDate.TimeOfDay > checking.reserveTime.TimeOfDay && _TimeDate.AddHours(AddHour).TimeOfDay > checking.reserveTime.TimeOfDay && _TimeDate.TimeOfDay < checking.reserveTime.AddHours(AddHour).TimeOfDay && _TimeDate.AddHours(AddHour).TimeOfDay > checking.reserveTime.AddHours(AddHour).TimeOfDay) { _check = false; } } return _check; }
public static string CreateScheduleA13(this IScheduleService s, string scheduleiCalendarValue, bool specialDaysSupported, out Schedule schedule, string specialDayGroupToken = "") { schedule = new Schedule { token = "", Name = "Test Name", Description = "Test Description", Standard = scheduleiCalendarValue, }; System.DateTime fromDate = new System.DateTime(System.DateTime.Now.Year, System.DateTime.Now.Month, System.DateTime.Now.Day, 22, 0, 0); if (specialDaysSupported) { schedule.SpecialDays = new SpecialDaysSchedule[] { new SpecialDaysSchedule { GroupToken = specialDayGroupToken, TimeRange = new TimePeriod[] { new TimePeriod { From = fromDate, Until = fromDate.AddHours(1), UntilSpecified = true } } } }; } return(CreateSchedule(s, schedule)); }
public void setFecha(int Mes, int Dia, int Hora) { Fecha = new System.DateTime(); Fecha.AddMonths(Mes); Fecha.AddDays(Dia); Fecha.AddHours(Hora); }
private void MyDataBind() { int k = 0; using (SqlConnection conn = new DB().GetConnection()) { string sql0 = "select * from [Hospital] where GUID = @HospitalGUID"; SqlCommand cmd = new SqlCommand(sql0, conn); cmd.Parameters.AddWithValue("@HospitalGUID", Session["HospitalGUID"].ToString()); conn.Open(); SqlDataReader rd = cmd.ExecuteReader(); if (rd.Read()) { k = Convert.ToInt16(rd["deadline"].ToString()); } rd.Close(); string sql = "select * from [Code_Cart] where CartGUID = @GUID"; cmd = new SqlCommand(sql, conn); cmd.Parameters.AddWithValue("@GUID", Request.QueryString["TGUID"].ToString()); rd = cmd.ExecuteReader(); if (rd.Read()) { System.DateTime Timers = System.DateTime.Parse(rd["CreateDate"].ToString()); DateTime T1 = Timers.AddHours(k); Time.Text = String.Format("{0:yyyy-MM-dd tt: hh:mm:ss}", T1); } rd.Close(); } }
//End of address parsing. //Date parsing conformant to RFC2822 and accepting RFC822 dates. public static System.DateTime ParseAsUniversalDateTime(string input) { input = Parser.ReplaceTimeZone(input); input = Parser.Clean(input); input = System.Text.RegularExpressions.Regex.Replace(input,@" +"," "); input = System.Text.RegularExpressions.Regex.Replace(input,@"( +: +)|(: +)|( +:)",":"); if(input.IndexOf(",")!=-1) { input = input.Replace(input.Split(',')[0]+", ",""); } string[] parts = input.Split(' '); int year = System.Convert.ToInt32(parts[2]); if(year<100) { if(year>49) year += 1900; else year += 2000; } int month = Parser.GetMonth(parts[1]); int day = System.Convert.ToInt32(parts[0]); string[] dateParts = parts[3].Split(':'); int hour = System.Convert.ToInt32(dateParts[0]); int minute = System.Convert.ToInt32(dateParts[1]); int second = 0; if(dateParts.Length>2) second = System.Convert.ToInt32(dateParts[2]); int offset_hours = System.Convert.ToInt32(parts[4].Substring(0,3)); int offset_minutes = System.Convert.ToInt32(parts[4].Substring(3,2)); System.DateTime date = new System.DateTime(year,month,day,hour,minute,second); date = date.AddHours(-offset_hours); date = date.AddMinutes(-offset_minutes); return date; }
public Session() { Description = string.Empty; Room = string.Empty; Start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 14, 30, 0); End = Start.AddHours(1); }
public static DateTime RetrieveLinkerTimestamp() //based on https://blog.codinghorror.com/determining-build-date-the-hard-way/ { string filePath = Assembly.GetExecutingAssembly().Location; const int peHeaderOffset = 60; const int linkerTimestampOffset = 8; var b = new byte[2048]; System.IO.FileStream s = null; try { s = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); s.Read(b, 0, 2048); } finally { if (s != null) { s.Close(); } } var dt = new System.DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(System.BitConverter.ToInt32(b, System.BitConverter.ToInt32(b, peHeaderOffset) + linkerTimestampOffset)); return(dt.AddHours(System.TimeZone.CurrentTimeZone.GetUtcOffset(dt).Hours)); }
private static DateTimeResolutionResult GetDateTimeResult(string unitStr, string numStr, System.DateTime referenceTime, bool future) { System.DateTime time; var ret = new DateTimeResolutionResult(); int futureOrPast = future ? 1 : -1; switch (unitStr) { case "H": time = referenceTime.AddHours(double.Parse(numStr) * futureOrPast); break; case "M": time = referenceTime.AddMinutes(double.Parse(numStr) * futureOrPast); break; case "S": time = referenceTime.AddSeconds(double.Parse(numStr) * futureOrPast); break; default: return(ret); } ret.Timex = $"{FormatUtil.LuisDateTime(time)}"; ret.FutureValue = ret.PastValue = time; ret.Success = true; return(ret); }
public static DateTime ConvertIntDatetime(double utc) { System.DateTime startTime = new System.DateTime(1970, 1, 1).ToLocalTime(); startTime = startTime.AddSeconds(utc); startTime = startTime.AddHours(8);//转化为北京时间(北京时间=UTC时间+8小时 ) return(startTime); }
public IhAHL(DateTime today) : base(ESport.Hockey_AHL) { if (string.IsNullOrWhiteSpace(this.sWebUrl)) { this.sWebUrl = @"http://theahl.com/stats/schedule.php?date="; } // 設定 this.AllianceID = 21; this.GameType = "IHUS2"; if (today.Date == DateTime.Now.Date)//以現在時間為基準去切換美東時間 { diffTime = frmMain.GetGameSourceTime("EasternTime");//取得與當地時間差(包含日光節約時間) if (diffTime > 0) this.GameDate = today.AddHours(-diffTime); else this.GameDate = GetUtcUsaEt(today);//取得美東時間 } else this.GameDate = today;//手動指定時間 //this.DownHome = new BasicDownload(this.Sport, @"http://theahl.com/stats/schedule.php"); // 以網站的資料頁面為主 this.DownHome = new BasicDownload(this.Sport, this.sWebUrl + this.GameDate.ToString("yyyy-MM-dd")); }
public void DefaultCalendarTest() { DateTime now = ClockProxy.Clock.Now; DateTime todayStart = new DateTime( now.Year, now.Month, now.Day ); for ( int dayHour = 0; dayHour < TimeSpec.HoursPerDay; dayHour++ ) { Hour hour = new Hour( todayStart.AddHours( dayHour ) ); Assert.AreEqual( hour.Year, todayStart.Year ); Assert.AreEqual( hour.Month, todayStart.Month ); Assert.AreEqual( hour.Month, todayStart.Month ); Assert.AreEqual( hour.Day, todayStart.Day ); Assert.AreEqual( hour.HourValue, dayHour ); Assert.AreEqual( hour.Start, todayStart.AddHours( dayHour ).Add( hour.Calendar.StartOffset ) ); Assert.AreEqual( hour.End, todayStart.AddHours( dayHour + 1 ).Add( hour.Calendar.EndOffset ) ); } }
public bool AdjustTimeForNextActivity() { if (RNG.Instance) { // Adjust the time parameters DateTimeForNextActivity.AddHours( Mathf.Clamp(RNG.Instance.Range(-MaxTimeHoursVariance, MaxTimeHoursVariance), 0, TimeController.HOURS_IN_DAY - 1)); DateTimeForNextActivity.AddMinutes( Mathf.Clamp(RNG.Instance.Range(-MaxTimeMinutesVariance, MaxTimeMinutesVariance), 0, TimeController.MINUTES_IN_HOUR - 1)); DateTimeForNextActivity.AddSeconds( Mathf.Clamp(RNG.Instance.Range(-MaxTimeSecondsVariance, MaxTimeSecondsVariance), 0, TimeController.SECONDS_IN_MINUTE - 1)); // ... then update the time controller using the adjusted time if (TimeController.Instance) { TimeController.Instance.SetTimeOfDay(DateTimeForNextActivity, false); return(true); } Debug.LogError("TimeController is not defined in the scene."); return(false); } Debug.LogError("RNG is not defined in the scene."); return(false); }
/// <summary> /// This method updates the x info texts. This should only be called, if the graph is entirely shown. /// </summary> private void UpdateXInfoTextFullShown(float xStep) { // ... and if the unit is a time unit, ... if (unit != xUnit.Units.NUMBER) { // ... set the x info texts. System.DateTime startDt = (System.DateTime)statistics.GetPoints()[0].GetX(); // ... update the x info text. for (int i = 0; i < xTexts.Count; i++) { xTexts[i].text = GetNameFromXObject(startDt.AddHours(xStep * (i + 1))); } } // Otherwise ... else { float startValue = (float)System.Convert.ToDouble(statistics.GetPoints()[0].GetX()); // ... just update the x info text with common numbers. for (int i = 0; i < xTexts.Count; i++) { xTexts[i].text = Round(startValue + xStep * (i + 1)) + ""; } } }
public static DateTime convert2datetime(double utc) { // System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(2010, 1, 1)); // 舊版本 System.DateTime startTime = TimeZoneInfo.ConvertTime(new System.DateTime(2010, 1, 1), TimeZoneInfo.Local); startTime = startTime.AddMilliseconds(utc); startTime = startTime.AddHours(8); return(startTime); }
DateTime getDate(double milliseconds) { DateTime day = new System.DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).ToLocalTime(); day = day.AddSeconds(milliseconds).ToLocalTime(); day = day.AddHours(1); return(day); }
public string GetSunSetTime() { System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); dateTime = dateTime.AddSeconds(Set); dateTime = dateTime.AddHours(2); return($"{dateTime.Hour}:{dateTime.Minute}"); }
/// <summary> /// 将Unix时间戳转换为DateTime类型时间 /// </summary> /// <param name="d">double 型数字</param> /// <returns>DateTime</returns> public static System.DateTime ConvertIntDateTime(double d) { System.DateTime time = System.DateTime.MinValue; System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); time = startTime.AddSeconds(d); time = time.AddHours(-8); return(time); }
/// <summary> /// 将c# DateTime时间格式转换为Unix时间戳格式 /// </summary> /// <param name="time">时间</param> /// <returns>int</returns> public static long ConvertDateTimeLong(System.DateTime time) { double intResult = 0; System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); //intResult = (time - startTime).TotalSeconds; intResult = (time.AddHours(8) - startTime).TotalSeconds; return((long)intResult); }
public static DateTime IntToDatetime(double utc) { System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); startTime = startTime.AddSeconds(utc); startTime = startTime.AddHours(8);//转化为北京时间(北京时间=UTC时间+8小时 ) return(startTime); }
void SetUpSun(int initialHoursToAdd) { // Calculate the offset based on the fact, that every hour, the cyclus goes on 15 degrees dayNightCycleOffset = dayStartAt * -15; // Add hours to define the beginning day time of the game inGameTime = inGameTime.AddHours(initialHoursToAdd); // Set the suns rotation to support the daytime sun.transform.rotation = Quaternion.Euler(new Vector3(GetSunRotationForTime(inGameTime.Hour, inGameTime.Minute), sun.transform.rotation.y, sun.transform.rotation.z)); }
public static System.DateTime Round(this System.DateTime dateTime, RoundTo rt) { System.DateTime rounded; switch (rt) { case RoundTo.Second: { rounded = new System.DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Kind); if (dateTime.Millisecond >= 500) { rounded = rounded.AddSeconds(1); } break; } case RoundTo.Minute: { rounded = new System.DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, 0, dateTime.Kind); if (dateTime.Second >= 30) { rounded = rounded.AddMinutes(1); } break; } case RoundTo.Hour: { rounded = new System.DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, 0, 0, dateTime.Kind); if (dateTime.Minute >= 30) { rounded = rounded.AddHours(1); } break; } case RoundTo.Day: { rounded = new System.DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0, dateTime.Kind); if (dateTime.Hour >= 12) { rounded = rounded.AddDays(1); } break; } default: { throw new ArgumentOutOfRangeException("rt"); } } return(rounded); }
public static Altova.Types.DateTime DatetimeFromDateAndTime(Altova.Types.DateTime date, Altova.Types.DateTime time) { Altova.Types.DateTime ret = new Altova.Types.DateTime(date); System.DateTime sysdt = ret.Value; sysdt = sysdt.AddHours(-date.Value.Hour + time.Value.Hour); sysdt = sysdt.AddMinutes(-date.Value.Minute + time.Value.Minute); sysdt = sysdt.AddSeconds(-date.Value.Second + time.Value.Second); sysdt = sysdt.AddMilliseconds(-date.Value.Millisecond + time.Value.Millisecond); ret.Value = sysdt; return(ret); }
private void startButton_Click(object sender, EventArgs e) { timer1 = new System.Windows.Forms.Timer(); timer1.Interval = 1000; timer1.Tick += new EventHandler(timer1_Tick); timer1.Enabled = true; System.DateTime firstTime = DateTime.Now; startTime.Text = (firstTime.Hour.ToString() + ":" + firstTime.Minute.ToString() + ":" + firstTime.Second.ToString()); System.DateTime secondTime = firstTime.AddHours(8); endTime.Text = (secondTime.Hour.ToString() + ":" + secondTime.Minute.ToString() + ":" + secondTime.Second.ToString()); }
public static DateObject SafeCreateFromValue(this DateObject datetime, int year, int month, int day, int hour, int minute, int second) { if (IsValidDate(year, month, day) && IsValidTime(hour, minute, second)) { datetime = datetime.SafeCreateFromValue(year, month, day); datetime = datetime.AddHours(hour - datetime.Hour); datetime = datetime.AddMinutes(minute - datetime.Minute); datetime = datetime.AddSeconds(second - datetime.Second); } return(datetime); }
System.DateTime ConvertPickerToTime() { int tempHour = System.Convert.ToInt32(this.GetComponent <UI_PickerWorkDayStartTime>().pickerParams[0].column[this.GetComponent <UI_PickerWorkDayStartTime>().pickerParams[0].selectedIndexReadOnly]); int tempMinute = System.Convert.ToInt32(this.GetComponent <UI_PickerWorkDayStartTime>().pickerParams[1].column[this.GetComponent <UI_PickerWorkDayStartTime>().pickerParams[1].selectedIndexReadOnly]); var NewTime = new System.DateTime(2013, 01, 01, tempHour, tempMinute, 0); if (this.GetComponent <UI_PickerWorkDayStartTime>().pickerParams[2].column[this.GetComponent <UI_PickerWorkDayStartTime>().pickerParams[2].selectedIndexReadOnly].ToString() == "PM") { NewTime = NewTime.AddHours(12); } return(NewTime); }
/// <summary> /// 将年龄转换为出生日期 /// </summary> /// <param name="age">年龄</param> /// <returns>出生日期</returns> public static DateTime GetDateTime(AgeValue age) { System.DateTime date = DateTime.Now; date = date.AddYears((-1) * age.Y_num); date = date.AddMonths((-1) * age.M_num); date = date.AddDays((-1) * age.D_num); date = date.AddHours((-1) * age.H_num); return(date); }
static void Main(string[] args) { // P7 - Date localization //Pedir al usuario que ingrese una fecha y hora System.Console.WriteLine("Escribe una fecha y hora: (yyyy - MM - dddd Hora : minuto : segundo) \n Exclusivamente en ese formato"); System.DateTime dateTyped = System.DateTime.Parse(Console.ReadLine()); System.Console.WriteLine("\nFecha introducida:"); System.Console.WriteLine(dateTyped); //fecha inicial //A partir de la fecha actual, obtener la fecha "dentro de 2 horas y 30 minutos" y mostrarla System.Console.WriteLine("\nHora despues de 2 horas y 30 minutos:"); dateTyped = dateTyped.AddHours(2).AddMinutes(30); System.Console.WriteLine(dateTyped); //Mostrar la fecha y hora actual en horario UTC System.DateTime actualDate = System.DateTime.UtcNow; System.Console.WriteLine($"\nHora UTC actual: {actualDate}"); //Mostrar la fecha y hora actual en horario de otro país y mencionar el nombre del país TimeZoneInfo otraZona = TimeZoneInfo.FindSystemTimeZoneById("Argentina Standard Time"); //aqui se puede obtener el standard time de cualquier pais System.DateTime horaArgentina = TimeZoneInfo.ConvertTime(System.DateTime.Now, otraZona); System.Console.WriteLine($"\nLa fecha y hora actual en Argentina es: {horaArgentina}"); //fuente: https://www.campusmvp.es/recursos/post/Cambios-de-zona-horaria-en-NET.aspx //Comparar la fecha y hora actual con la fecha y hora ingresada. //Si la fecha ingresada está en el futuro, mostrar cuántos días faltan. //Si la fecha ingresada está en el pasado, mostrar cuántos días han transcurrido System.Console.WriteLine("\n"); if (dateTyped < System.DateTime.Now) //past { TimeSpan timeDif = System.DateTime.Now - dateTyped; System.Console.WriteLine($"{timeDif.Days} dias transcurridos desde fecha ingresada "); } else if (dateTyped == System.DateTime.Now) { System.Console.WriteLine("{0:d} es la fecha de hoy!", dateTyped); } else // compareValue > 0 future { TimeSpan timeDif = dateTyped - System.DateTime.Now; System.Console.WriteLine($"{timeDif.Days} dias por transcurrir desde fecha ingresada"); } }
static void Main() { Console.Write("Enter date in the the format d.m.y h:m:s: "); string fullDate = Console.ReadLine(); //withouth validation because the code will become too long //the validation is the same as the prev ex string[] parts = fullDate.Split(' '); string[] date = parts[0].Split('.'); string[] time = parts[1].Split(':'); int day = int.Parse(date[0]); int month = int.Parse(date[1]); int year = int.Parse(date[2]); int hours = int.Parse(time[0]); int minutes = int.Parse(time[1]); int seconds = int.Parse(time[2]); System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("bg-BG"); //27.1.2013 21:21:43 DateTime result = new DateTime(year, month, day, hours, minutes, seconds); Console.WriteLine(result.AddHours(6.5)); Console.WriteLine(result.AddHours(6.5).DayOfWeek); }