public static void InitRTC() { if (_realTimeClock != null) { return; } _realTimeClock = new RTC_DS3231(() => { DateTime?realTime = _realTimeClock.ReadTime(); DateTimeOffset rtcTime = new DateTimeOffset(_realTimeClock.ReadTime().Value, TimeSpan.Zero); CurrentDate = rtcTime.ToLocalTime(); CurrentTime = rtcTime.ToLocalTime().TimeOfDay; SetSystemTime(); //DispatcherTimer timer = new DispatcherTimer(); //timer.Interval = TimeSpan.FromSeconds(1); //timer.Tick += (oo, ee) => // { // SetSystemTime(); // ReportedTime = DateTime.Now; // SystemDateTime = _realTimeClock.ReadTime().Value; // }; // timer.Start(); }); }
/// <summary> /// 转时间为友好文字的核心代码 /// </summary> /// <param name="time"></param> /// <returns></returns> public string ConvertTime(DateTimeOffset time) { //if it is today.. if (time.Date == DateTimeOffset.UtcNow.Date) { return(time.ToLocalTime().ToString("HH:mm:ss")); } //Otherwise, return a full date that include year and month return(time.ToLocalTime().ToString("MM dd, HH:mm"));// }
protected override object ParseValue(PropertyInfo property, object target, object value) { if (value == null) { return(property.PropertyType.GetDefault()); } else { if (property.PropertyType.IsDateTime() && value.GetType().IsNumeric()) { DateTimeOffset d = DateTimeOffset.FromUnixTimeMilliseconds((long)Convert.ChangeType(value, typeof(long))); if (property.PropertyType.IsAssignableFrom(typeof(DateTimeOffset))) { return(d.ToLocalTime()); } else { return(d.ToLocalTime().DateTime); } } else if (property.PropertyType.IsTimeSpan() && value.GetType().IsNumeric()) { return(TimeSpan.FromMilliseconds((long)Convert.ChangeType(value, typeof(long)))); } else if ((property.PropertyType == typeof(Guid) || property.PropertyType == typeof(Guid?)) && (value.GetType() == typeof(Guid) || value.GetType() == typeof(Guid?))) { return(value?.ToString()); } else if ((property.PropertyType == typeof(Guid) || property.PropertyType == typeof(Guid?)) && value.GetType() == typeof(string)) { return(Guid.Parse(value.ToString())); } else if (value.GetType() != property.PropertyType) { string convName = $"{value.GetType().FullName}{property.PropertyType.FullName}"; if (!_converters.ContainsKey(convName)) { ParameterExpression p = Expression.Parameter(typeof(object)); Func <object, object> converter = Expression.Lambda <Func <object, object> >( Expression.Convert(Expression.Convert(Expression.Convert(p, value.GetType()), property.PropertyType), typeof(object)), p ).Compile(); _converters.Add(convName, converter); } return(_converters[convName](value)); } else { return(value); } } }
private void tickOnMidnight(DateTimeOffset now) { var localNow = now.ToLocalTime(); if (localNow.Date != previousSecondLocalDateTime.Date) { midnightSubject.OnNext(localNow); } previousSecondLocalDateTime = now.ToLocalTime(); }
public static string Convert(DateTimeOffset offset, CultureInfo cultureInfo = null) { if (offset.ToLocalTime().Date == DateTimeOffset.Now.Date) { return(Resources.Today); } if (offset.ToLocalTime().Date.AddDays(1) == DateTimeOffset.Now.Date) { return(Resources.Yesterday); } return(offset.ToString("ddd, dd MMM", cultureInfo ?? CultureInfo.CreateSpecificCulture("en-US"))); }
public static string GetFriendlyDateFromFormat(this DateTimeOffset d, string returnFormat, bool isDetailed = false) { var elapsed = DateTimeOffset.Now - d; if (d.Year == 1601 || d.Year == 9999) { return(" "); } else if (isDetailed && returnFormat != "g" && elapsed.TotalDays < 7) { return(d.ToLocalTime().ToString(returnFormat) + " " + d.ToLocalTime().ToString("t") + " (" + GetFriendlyDateFromFormat(d, returnFormat) + ")"); } else if (isDetailed && returnFormat != "g") { return(d.ToLocalTime().ToString(returnFormat) + " " + d.ToLocalTime().ToString("t")); } else if (elapsed.TotalDays >= 7 || returnFormat == "g") { return(d.ToLocalTime().ToString(returnFormat)); } else if (elapsed.TotalDays >= 2) { return(string.Format("DaysAgo".GetLocalized(), elapsed.Days)); } else if (elapsed.TotalDays >= 1) { return(string.Format("DayAgo".GetLocalized(), elapsed.Days)); } else if (elapsed.TotalHours >= 2) { return(string.Format("HoursAgo".GetLocalized(), elapsed.Hours)); } else if (elapsed.TotalHours >= 1) { return(string.Format("HourAgo".GetLocalized(), elapsed.Hours)); } else if (elapsed.TotalMinutes >= 2) { return(string.Format("MinutesAgo".GetLocalized(), elapsed.Minutes)); } else if (elapsed.TotalMinutes >= 1) { return(string.Format("MinuteAgo".GetLocalized(), elapsed.Minutes)); } else { return(string.Format("SecondsAgo".GetLocalized(), elapsed.Seconds)); } }
public static int GetIso8601WeekOfYear(DateTimeOffset time) { // Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll // be the same week# as whatever Thursday, Friday or Saturday are, // and we always get those right DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time.ToLocalTime().DateTime); if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday) { time = time.AddDays(3); } // Return the week of our adjusted day return(CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time.ToLocalTime().DateTime, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday)); }
public static IQueryable <TransparentAdministrationMonitorLog> GetByDateInterval(this IRepository <TransparentAdministrationMonitorLog> repository, DateTimeOffset dateFrom, DateTimeOffset dateTo, string userName, short?idContainer, int?environment) { dateTo = new DateTimeOffset(dateTo.ToLocalTime().Date.AddDays(1)); IQueryable <TransparentAdministrationMonitorLog> results = repository .Query(x => x.Date >= dateFrom && x.Date <= dateTo, optimization: true) .Include(f => f.DocumentUnit) .Include(f => f.Role) .SelectAsQueryable(); if (!string.IsNullOrEmpty(userName)) { results = results.Where(f => f.RegistrationUser.Contains(userName)); } if (idContainer.HasValue) { results = results.Where(f => f.DocumentUnit.Container.EntityShortId == idContainer.Value); } if (environment.HasValue) { if (environment < 100) { results = results.Where(f => f.DocumentUnit.Environment == environment.Value); } if (environment >= 100) { results = results.Where(f => f.DocumentUnit.Environment >= environment.Value); } } return(results); }
internal static void ConvertToManaged(out DateTimeOffset managedLocalDTO, ref DateTimeNative nativeTicks) { long ticks = 504911232000000000L + nativeTicks.UniversalTime; DateTimeOffset dateTimeOffset = new DateTimeOffset(ticks, TimeSpan.Zero); managedLocalDTO = dateTimeOffset.ToLocalTime(true); }
public static Stream CreateFileGroupDescriptorW(string fileName, DateTimeOffset lastWriteTime) { var fileGroupDescriptor = new FILEGROUPDESCRIPTORW() { cItems = 1 }; var fileDescriptor = new FILEDESCRIPTORW() { cFileName = fileName }; fileDescriptor.dwFlags |= FD_SHOWPROGRESSUI; fileDescriptor.dwFlags |= FD_CREATETIME | FD_WRITESTIME; var changeTime = lastWriteTime.ToLocalTime().ToFileTime(); var changeTimeFileTime = new System.Runtime.InteropServices.ComTypes.FILETIME { dwLowDateTime = (int)(changeTime & 0xffffffff), dwHighDateTime = (int)(changeTime >> 32), }; fileDescriptor.ftLastWriteTime = changeTimeFileTime; fileDescriptor.ftCreationTime = changeTimeFileTime; var fileGroupDescriptorBytes = StructureBytes(fileGroupDescriptor); var fileDescriptorBytes = StructureBytes(fileDescriptor); var memoryStream = new MemoryStream(); memoryStream.Write(fileGroupDescriptorBytes, 0, fileGroupDescriptorBytes.Length); memoryStream.Write(fileDescriptorBytes, 0, fileDescriptorBytes.Length); return(memoryStream); }
/// <summary> /// Determines whether the specified date is the same day as the utc date. /// </summary> /// <param name="date">The date.</param> /// <param name="utcDate">The UTC date.</param> /// <returns></returns> public static bool IsSameDate(this DateTime date, DateTime utcDate) { var d1 = new DateTimeOffset(date); var d2 = new DateTimeOffset(utcDate); return(DateTime.Compare(d1.ToLocalTime().Date, d2.ToLocalTime().Date) == 0); }
public string GenerateTextline() { string msg = "[" + Date.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss") + "]"; msg += " " + VKTools.GetProfile("", FromID).name; var MsgText = Text.Replace("\n", "\t"); msg += ": " + MsgText; if (Attachments.Count > 0) { msg += " [" + Attachments.Count + " attachments: "; for (var a = 0; a < Attachments.Count; a++) { if (a > 0) { msg += ","; } msg += Attachments[a].Type; if (!string.IsNullOrEmpty(Attachments[a].Filename)) { msg += " '" + Attachments[a].Filename + "'"; } } msg += "]"; } return(msg); }
private void PostToastNotification(TravelCard card) { DateTimeOffset youngestValueExpiration = card.PeriodEndDate1 > card.PeriodEndDate2 ? card.PeriodEndDate1 : card.PeriodEndDate2; ToastVisual visual = new ToastVisual() { BindingGeneric = new ToastBindingGeneric() { Children = { new AdaptiveText() { Text = $"Remaining value: {(card.ValueTotalCents / 100m).ToString("#.##")} €\n" + $"Season pass expires: {youngestValueExpiration.ToLocalTime().ToString(DateTimeFormatInfo.CurrentInfo.ShortDatePattern)}", HintMaxLines = 2 }, new AdaptiveText() { Text = $"Card {card.CardNumber}\n" } } }, }; ToastContent content = new ToastContent { Visual = visual, Scenario = ToastScenario.Default }; var toast = new ToastNotification(content.GetXml()); ToastNotificationManager.CreateToastNotifier().Show(toast); }
public static String ToDelphiTime(this DateTimeOffset time) { time = time.ToLocalTime(); var totaltime = String.Format("{0:0.00000000}", (time.Hour * 60 + time.Minute) / (24d * 60d)).Remove(0, 2); return(totaltime); }
public static String ToDelphiDate(this DateTimeOffset date) { date = date.ToLocalTime(); var totaldays = ((int)(date - (DateTimeOffset.ParseExact("30.12.1899", "dd.MM.yyyy", CultureInfo.InvariantCulture))).TotalDays).ToString(); return(totaldays); }
public static String ToTimeString(this DateTimeOffset datetime) { datetime = datetime.ToLocalTime(); var time = ToUrlString(datetime.ToString("HH:mm", CultureInfo.InvariantCulture)); return(time); }
public ChannelMessage(string id, DateTimeOffset when, string userName, string content) { this.Id = id; this.When = when.ToLocalTime(); this.User = userName; this.Content = content; }
/// <summary> /// Determines whether the specified date is today. /// </summary> /// <param name="date">The date.</param> /// <returns></returns> public static bool IsToday(this DateTime date) { var d1 = new DateTimeOffset(date); var d2 = new DateTimeOffset(DateTime.UtcNow); return(DateTime.Compare(d1.ToLocalTime().Date, d2.ToLocalTime().Date) == 0); }
public static NowTime GetNowTime() { NowTime timeParam = new NowTime(); timeParam.day = DateTime.Now.ToString(@"yyyy-MM-dd"); DateTimeOffset offset = DateTimeOffset.Now; // utc now in seconds timeParam.now = offset.ToUnixTimeSeconds(); timeParam.now_dt = DateTime.Now; // set the offset (will be negative before utc and positive after) timeParam.offset_minutes = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).TotalMinutes; timeParam.offset_seconds = timeParam.offset_minutes * 60; // local now in seconds timeParam.local_now = Convert.ToInt64(timeParam.now + timeParam.offset_seconds); timeParam.local_day = offset.ToLocalTime().ToString(@"yyyy-MM-dd"); // start and end of day timeParam.start_of_today = StartOfDay(); timeParam.local_start_of_day = Convert.ToInt64(((DateTimeOffset)timeParam.start_of_today).ToUnixTimeSeconds() + timeParam.offset_seconds); timeParam.local_end_of_day = Convert.ToInt64(EndOfDay() + timeParam.offset_seconds); timeParam.utc_end_of_day = EndOfDay(); // yesterday start timeParam.start_of_yesterday_dt = StartOfYesterday(); timeParam.local_start_of_yesterday = Convert.ToInt64(((DateTimeOffset)timeParam.start_of_yesterday_dt).ToUnixTimeSeconds() + timeParam.offset_seconds); // week start timeParam.start_of_week_dt = StartOfWeek(); timeParam.local_start_of_week = Convert.ToInt64(((DateTimeOffset)timeParam.start_of_week_dt).ToUnixTimeSeconds() + timeParam.offset_seconds); return(timeParam); }
private DateTimeOffset nextLocalMidnight(DateTimeOffset now) { var dayFromNow = now.ToLocalTime().AddDays(1); var date = new DateTime(dayFromNow.Year, dayFromNow.Month, dayFromNow.Day); return(new DateTimeOffset(date, TimeZoneInfo.Local.GetUtcOffset(date)).ToUniversalTime()); }
public DateTimeOffset getLocalTime(DateTime dateTime) { var tzi = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneId); DateTimeOffset utcTime = DateTime.SpecifyKind(dateTime - tzi.GetUtcOffset(dateTime), DateTimeKind.Utc); return(utcTime.ToLocalTime()); }
public static String ToDateString(this DateTimeOffset datetime) { datetime = datetime.ToLocalTime(); var date = datetime.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture); return(date); }
public static string ToDaysAgo(this DateTimeOffset d) { var dt = DateTimeOffset.Now.ToLocalTime().Subtract(d.ToLocalTime()); if (dt.TotalDays >= 365) { var years = Convert.ToInt32(dt.TotalDays) / 365; return(years + (years > 1 ? " years ago" : " year ago")); } if (dt.TotalDays >= 30) { var months = Convert.ToInt32(dt.TotalDays) / 30; return(months + (months > 1 ? " months ago" : " month ago")); } if (dt.TotalDays > 1) { var days = Convert.ToInt32(dt.TotalDays); return(days + (days > 1 ? " days ago" : " day ago")); } if (dt.TotalHours > 1) { var hours = Convert.ToInt32(dt.TotalHours); return(hours + (hours > 1 ? " hours ago" : " hour ago")); } if (dt.TotalMinutes > 1) { var minutes = Convert.ToInt32(dt.TotalMinutes); return(minutes + (minutes > 1 ? " minutes ago" : " minute ago")); } return("moments ago"); }
/// <summary> /// Determine the next time (in milliseconds) that is 'included' by the /// Calendar after the given time. Return the original value if timeStamp is /// included. Return DateTime.MinValue if all days are excluded. /// <para> /// Note that this Calendar is only has full-day precision. /// </para> /// </summary> /// <param name="timeUtc"></param> /// <returns></returns> public override DateTimeOffset GetNextIncludedTimeUtc(DateTimeOffset timeUtc) { if (base.AreAllDaysExcluded()) { return DateTime.MinValue; } // Call base calendar implementation first DateTimeOffset baseTime = base.GetNextIncludedTimeUtc(timeUtc); if ((baseTime != DateTimeOffset.MinValue) && (baseTime > timeUtc)) { timeUtc = baseTime; } // Get timestamp for 00:00:00 //DateTime d = timeUtc.Date; --commented out for local time impl DateTime d = timeUtc.ToLocalTime().Date; if (!IsDayExcluded(d.DayOfWeek)) { return timeUtc; } // return the original value while (IsDayExcluded(d.DayOfWeek)) { d = d.AddDays(1); } return d; }
public void GetJobDetails_ForExistingJob_ReturnsCorrectInfo() { IJobDetail job = GetMockJob("job1", "SOD"); var trigger = MockRepository.GenerateMock <ITrigger>(); DateTimeOffset triggerTime = new DateTimeOffset(DateTime.UtcNow.AddMinutes(5)); trigger.Expect(t => t.GetNextFireTimeUtc()).Return(triggerTime).Repeat.Twice(); var triggers = new List <ITrigger>() { trigger }; _mockScheduler.Expect(s => s.GetJobDetail(Arg <JobKey> .Is.TypeOf)).Return(job); _mockScheduler.Expect(s => s.GetTriggersOfJob(Arg <JobKey> .Is.TypeOf)).Return(triggers); var result = _interactor.GetJobDetails("SOD.job1"); Assert.AreEqual("SOD.job1", result.Name); Assert.AreEqual("this does something", result.Description); bool isLocalInDaylightSavingTime = TimeZoneInfo.Local.IsDaylightSavingTime(triggerTime.LocalDateTime); var localTimeZoneName = isLocalInDaylightSavingTime ? TimeZoneInfo.Local.DaylightName : TimeZoneInfo.Local.StandardName; Assert.IsTrue(result.NextRunAt.StartsWith(triggerTime.ToLocalTime().ToString("F") + " " + localTimeZoneName)); Assert.AreEqual(2, result.Properties.Count); Assert.AreEqual("something", result.Properties.FirstOrDefault(p => p.Key == "prop1").Value); Assert.AreEqual("something else", result.Properties.FirstOrDefault(p => p.Key == "prop2").Value); job.VerifyAllExpectations(); trigger.VerifyAllExpectations(); }
/// <summary> /// This method converts the property by negating its boolean value it. /// </summary> /// <param name="value">the property value</param> /// <param name="targetType">The object type</param> /// <param name="parameter">The command parameter</param> /// <param name="culture">The culture info</param> /// <returns>The converted property</returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { DateTimeOffset input = (DateTimeOffset)value; DateTimeOffset empty; string output = string.Empty; if (input != null && input.Year != empty.Year) { output = input.ToLocalTime().Day.ToString("00") + "/" + input.ToLocalTime().Month.ToString("00") + " - " + input.ToLocalTime().Hour.ToString("00") + ":" + input.ToLocalTime().Minute.ToString("00"); } else { output = "--/-- - --:--"; } return(output); }
public UserDonationModel ToGenericDonation() { double amount = 0.0; if (this.amount.HasValue) { amount = this.amount.GetValueOrDefault(); } DateTimeOffset datetime = DateTimeOffset.Now; if (!string.IsNullOrEmpty(this.createdDateUTC) && DateTimeOffset.TryParse(this.createdDateUTC, out datetime)) { datetime = datetime.ToLocalTime(); } return(new UserDonationModel() { Source = UserDonationSourceEnum.ExtraLife, ID = this.donorID, UserName = this.displayName, Message = this.message, ImageLink = this.avatarImageURL, Amount = Math.Round(amount, 2), DateTime = datetime, }); }
public PlayedOnText(DateTimeOffset time) { Anchor = Anchor.BottomCentre; Origin = Anchor.BottomCentre; Font = OsuFont.GetFont(size: 10, weight: FontWeight.SemiBold); Text = $"Played on {time.ToLocalTime():d MMMM yyyy HH:mm}"; }
public MeMessage(DateTimeOffset when, string userName, string content) { this.Content = content; this.When = when.ToLocalTime(); this.Time = this.When.ToString("h:mm:ss tt"); this.User = userName; }
public static string GetUploadTimeString(DateTimeOffset uploadTimeOffset) { DateTime uploadTime = uploadTimeOffset.ToLocalTime().DateTime; DateTime currentTime = DateTime.Now; TimeSpan timeDelta = currentTime - uploadTime; string result = uploadTime.ToString("yyyy-MM-dd HH:mm:ss"); if (timeDelta.TotalMinutes < 2) { result += " (just now)"; } else if (timeDelta.TotalHours < 2) { result += $" ({(int)timeDelta.TotalMinutes} minutes ago)"; } else if (timeDelta.TotalDays < 2) { result += $" ({(int)timeDelta.TotalHours} hours ago)"; } return(result); }
public DrawableDate(DateTimeOffset date) { AutoSizeAxes = Axes.Both; Font = "Exo2.0-RegularItalic"; this.date = date.ToLocalTime(); }
public static XElement TIME(string name, DateTimeOffset time) { var t1 = time.ToUniversalTime(); var t2 = time.ToLocalTime().ToString("G"); return new XElement( XN.time, PROP(name), new XAttribute(XN.datetime, t1), t2); }
public DateTimeOffset ScheduleNextTime(DateTimeOffset currentTime, JobExecutionRecord lastExecution) { var localTime = currentTime.ToLocalTime(); var oneAmToday = new DateTime(localTime.Year, localTime.Month, localTime.Day, _hour, _minute, 0, 0, DateTimeKind.Local); var nextScheduledTime = oneAmToday; if (localTime.Hour > _hour || (localTime.Hour == _hour && localTime.Minute >= _minute)) { // Switch to tomorrow nextScheduledTime = oneAmToday.AddDays(1); } return nextScheduledTime.ToUniversalTime(); }
public static string OffsetUtc(DateTimeOffset time) { if (time == default(DateTimeOffset)) return ""; var now = DateTimeOffset.UtcNow; var offset = now - time; if (Math.Abs(offset.TotalDays) > 7) { return time.ToLocalTime().ToString("MMMM dd, yyyy", CultureInfo.InvariantCulture); } if (offset > TimeSpan.Zero) { return PositiveTimeSpan(offset) + " ago"; } return PositiveTimeSpan(-offset) + " from now"; }
public static void ToLocalTime() { DateTimeOffset dateTimeOffset = new DateTimeOffset(new DateTime(1000, DateTimeKind.Utc)); Assert.Equal(new DateTimeOffset(dateTimeOffset.UtcDateTime.ToLocalTime()), dateTimeOffset.ToLocalTime()); }
private static string ConvertTime(DateTimeOffset time) { if (time == DateTimeOffset.MinValue) return "n/a"; return time.ToLocalTime().ToString("s").Replace("T", " "); }
/// <summary> /// Gets the statistical information /// </summary> /// <param name="totalCasesNum">The number of total cases</param> /// <param name="passedNum">The number of passed cases</param> /// <param name="failedNum">The number of failed cases</param> /// <param name="testRunStartTime">The start time of the run</param> /// <param name="testRunEndTime">The end time of the run</param> /// <returns>Return statistical information about this test</returns> public string SummaryTable(long totalCasesNum, long passedNum, long failedNum, DateTimeOffset testRunStartTime, DateTimeOffset testRunEndTime) { DataType.RunSummary sry = new DataType.RunSummary() { TotalCount = totalCasesNum, FailedCount = failedNum, PassedCount = passedNum, InconclusiveCount = totalCasesNum - passedNum - failedNum, PassRate = totalCasesNum == 0 ? 0 : (float)passedNum * 100 / totalCasesNum, StartTime = testRunStartTime.ToLocalTime().ToString("MM/dd/yyyy HH:mm:ss"), EndTime = testRunEndTime.ToLocalTime().ToString("MM/dd/yyyy HH:mm:ss"), Duration = testRunEndTime.Subtract(testRunStartTime).ToString(@"hh\:mm\:ss") }; return (serializer.Serialize(sry)); }
public static string GenerateHeader(string authorName, string authorFullEmail,string authoredAge, DateTimeOffset authorTime, string committerName, string committerFullEmail,string commitedAge, DateTimeOffset commitTime, Guid commitGuid) { var authorField =GenerateHeaderField( Strings.GetAuthorText()); var authorDateField=GenerateHeaderField(Strings.GetAuthorDateText()); var committerField = GenerateHeaderField(Strings.GetCommitterText()); var commitDate = GenerateHeaderField(Strings.GetCommitDateText()); var commitHashField = GenerateHeaderField(Strings.GetCommitHashText()); var authorEmail = GetEmail(authorFullEmail); var committerEmail = GetEmail(committerFullEmail); var expectedHeader = authorField + "<a href='mailto:" + HttpUtility.HtmlAttributeEncode(authorEmail) + "'>" + HttpUtility.HtmlEncode(authorFullEmail) + "</a>" + Environment.NewLine + authorDateField + authoredAge + " (" + authorTime.ToLocalTime().ToString("ddd MMM dd HH':'mm':'ss yyyy") + ")" + Environment.NewLine + committerField + "<a href='mailto:" + HttpUtility.HtmlAttributeEncode(committerEmail) + "'>" + HttpUtility.HtmlEncode(committerFullEmail) + "</a>" + Environment.NewLine + commitDate+commitedAge+" (" + commitTime.ToLocalTime().ToString("ddd MMM dd HH':'mm':'ss yyyy") + ")" + Environment.NewLine + commitHashField + commitGuid; return expectedHeader; }
public void RunAsync(bool isRerun, DateTimeOffset firstRunTimestamp, Action<string> callback) { new Thread(() => { string outputMessage = _outputMessage; #region temporal analysis for rerun if (isRerun && !string.IsNullOrWhiteSpace(_outputMessageRerun)) { TimeSpan promptAge = DateTimeOffset.UtcNow - firstRunTimestamp; int daysAgo = (int)promptAge.TotalDays; string daysAgoStr; if (daysAgo == 0) daysAgoStr = "today"; else if (daysAgo == 1) daysAgoStr = "yesterday"; else daysAgoStr = promptAge.TotalDays + " days ago"; outputMessage = string.Format(_outputMessageRerun, daysAgoStr + " at " + firstRunTimestamp.ToLocalTime().DateTime.ToString("h:mm tt")); } #endregion SensusServiceHelper.Get().TextToSpeechAsync(outputMessage, () => { SensusServiceHelper.Get().RunVoicePromptAsync(outputMessage, response => { Viewed = true; if (string.IsNullOrWhiteSpace(response)) response = null; _response = response; Complete = _response != null; callback(_response); }); }); }).Start(); }
/// <summary> /// Returns the next time at which the <see cref="IDailyTimeIntervalTrigger" /> will /// fire, after the given time. If the trigger will not fire after the given /// time, <see langword="null" /> will be returned. /// </summary> /// <param name="afterTime"></param> /// <returns></returns> public override DateTimeOffset? GetFireTimeAfter(DateTimeOffset? afterTime) { // Check if trigger has completed or not. if (complete) { return null; } // Check repeatCount limit if (repeatCount != RepeatIndefinitely && timesTriggered > repeatCount) { return null; } // a. Increment afterTime by a second, so that we are comparing against a time after it! if (afterTime == null) { afterTime = SystemTime.UtcNow().AddSeconds(1); } else { afterTime = afterTime.Value.AddSeconds(1); } // now change to local time zone afterTime = afterTime.Value.ToLocalTime(); // b.Check to see if afterTime is after endTimeOfDay or not. // If yes, then we need to advance to next day as well. bool afterTimePassEndTimeOfDay = false; if (endTimeOfDay != null) { afterTimePassEndTimeOfDay = afterTime.Value > endTimeOfDay.GetTimeOfDayForDate(afterTime).Value; } DateTimeOffset? fireTime = AdvanceToNextDayOfWeek(afterTime.Value, afterTimePassEndTimeOfDay); if (fireTime == null) { return null; } // c. Calculate and save fireTimeEndDate variable for later use DateTimeOffset fireTimeEndDate; if (endTimeOfDay == null) { fireTimeEndDate = new TimeOfDay(23, 59, 59).GetTimeOfDayForDate(fireTime).Value; } else { fireTimeEndDate = endTimeOfDay.GetTimeOfDayForDate(fireTime).Value; } // e. Check fireTime against startTime or startTimeOfDay to see which go first. DateTimeOffset fireTimeStartDate = startTimeOfDay.GetTimeOfDayForDate(fireTime).Value; if (fireTime < startTimeUtc && startTimeUtc < fireTimeStartDate) { return fireTimeStartDate; } else if (fireTime < startTimeUtc && startTimeUtc > fireTimeStartDate) { return startTimeUtc; } else if (fireTime > startTimeUtc && fireTime < fireTimeStartDate) { return fireTimeStartDate; } // Always adjust the startTime to be startTimeOfDay startTimeUtc = fireTimeStartDate.ToUniversalTime(); // f. Continue to calculate the fireTime by incremental unit of intervals. long secondsAfterStart = (long) (fireTime.Value - startTimeUtc.ToLocalTime()).TotalSeconds; long repeatLong = RepeatInterval; DateTimeOffset sTime = startTimeUtc.ToLocalTime(); IntervalUnit repeatUnit = RepeatIntervalUnit; if (repeatUnit == IntervalUnit.Second) { long jumpCount = secondsAfterStart/repeatLong; if (secondsAfterStart%repeatLong != 0) { jumpCount++; } sTime = sTime.AddSeconds(RepeatInterval*(int) jumpCount); fireTime = sTime; } else if (repeatUnit == IntervalUnit.Minute) { long jumpCount = secondsAfterStart/(repeatLong*60L); if (secondsAfterStart%(repeatLong*60L) != 0) { jumpCount++; } sTime = sTime.AddMinutes(RepeatInterval*(int) jumpCount); fireTime = sTime; } else if (repeatUnit == IntervalUnit.Hour) { long jumpCount = secondsAfterStart/(repeatLong*60L*60L); if (secondsAfterStart%(repeatLong*60L*60L) != 0) { jumpCount++; } sTime = sTime.AddHours(RepeatInterval*(int) jumpCount); fireTime = sTime; } // g. Ensure this new fireTime is within one day, or else we need to advance to next day. if (fireTime > fireTimeEndDate) { // Check to see if fireTime has pass fireTime's end of day. If not, we need to advance by one day. DateTimeOffset fireTimeEndOfDay = new TimeOfDay(23, 59, 59).GetTimeOfDayForDate(fireTimeEndDate).Value; if (fireTime > fireTimeEndOfDay) { fireTime = AdvanceToNextDayOfWeek(fireTime.Value, false); } else { fireTime = AdvanceToNextDayOfWeek(fireTime.Value, true); } if (fireTime == null) { return null; } // Check to see if next day fireTime is before startTimeOfDay, if not, we need to set to startTimeOfDay. DateTimeOffset nextDayfireTimeStartDate = StartTimeOfDay.GetTimeOfDayForDate(fireTime).Value; if (fireTime < nextDayfireTimeStartDate) { fireTime = nextDayfireTimeStartDate; } } // i. Return calculated fireTime. return fireTime.Value.ToUniversalTime(); }
/// <summary> /// Determine whether the given time (in milliseconds) is 'included' by the /// Calendar. /// <para> /// Note that this Calendar is only has full-day precision. /// </para> /// </summary> /// <param name="timeUtc"></param> /// <returns></returns> public override bool IsTimeIncluded(DateTimeOffset timeUtc) { DateTimeOffset localTime = timeUtc.ToLocalTime(); return base.IsTimeIncluded(localTime); }
internal static DateTimeOffset GetLastAccessTime(string path) { string str = LongPath.NormalizePath(path); new FileIOPermission(FileIOPermissionAccess.Read, new string[] { str }, false, false).Demand(); string str2 = Path.AddLongPathPrefix(str); Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = File.FillAttributeInfo(str2, ref data, false, false); if (errorCode != 0) { __Error.WinIOError(errorCode, str); } long fileTime = (data.ftLastAccessTimeHigh << 0x20) | data.ftLastAccessTimeLow; DateTimeOffset offset = new DateTimeOffset(DateTime.FromFileTimeUtc(fileTime).ToLocalTime()); return offset.ToLocalTime(); }
public NotificationMessage(DateTimeOffset when, string content) { this.When = when.ToLocalTime(); this.Time = this.When.ToString("h:mm:ss tt"); this.Content = content; }
private DateTimeOffset CreateCalendarTime(DateTimeOffset dateTime) { return dateTime.ToLocalTime(); }
private string GetTimeString(DateTimeOffset date) { date = date.ToLocalTime(); DateTimeOffset today = DateTimeOffset.Now; if (today.Date == date.Date) return "at " + date.ToString("HH:mm"); else if (today.Date.Subtract(new TimeSpan(6, 0, 0, 0)) <= date) return "on " + date.ToString("ddd, HH:mm"); else return "on " + date.ToString("dd MMM, HH:mm"); }
private static int Main(string[] args) { CommandLineParser clp = new CommandLineParser(); clp.AddKnownOption("a", "assembly-info"); clp.AddKnownOption("", "test-b36min"); clp.AddKnownOption("b", "test-bmin"); clp.AddKnownOption("f", "format", true); clp.AddKnownOption("h", "help"); clp.AddKnownOption("i", "ignore-missing"); clp.AddKnownOption("m", "multi-project"); clp.AddKnownOption("r", "revision"); clp.AddKnownOption("s", "restore"); clp.AddKnownOption("v", "version"); clp.AddKnownOption("x", "test-xmin"); clp.AddKnownOption("B", "de-bmin"); clp.AddKnownOption("", "de-b36min"); clp.AddKnownOption("D", "de-dmin"); clp.AddKnownOption("I", "only-infver"); clp.AddKnownOption("M", "stop-if-modified"); clp.AddKnownOption("X", "de-xmin"); clp.AddKnownOption("", "debug"); debugOutput = clp.IsOptionSet("debug"); if (clp.IsOptionSet("h") || clp.IsOptionSet("v")) { HandleHelp(clp.IsOptionSet("h")); return 0; } if (clp.IsOptionSet("X")) { int baseYear; if (!int.TryParse(clp.GetArgument(0), out baseYear)) { Console.Error.WriteLine("Invalid argument: Base year expected"); return 1; } string xmin = clp.GetArgument(1).Trim().ToLowerInvariant(); DateTime time = DehexMinutes(baseYear, xmin); if (time == DateTime.MinValue) { Console.Error.WriteLine("Invalid xmin value."); return 0; } Console.WriteLine(time.ToString("yyyy-MM-dd HH:mm") + " UTC"); Console.WriteLine(time.ToLocalTime().ToString("yyyy-MM-dd HH:mm K")); return 0; } if (clp.IsOptionSet("B")) { int baseYear; if (!int.TryParse(clp.GetArgument(0), out baseYear)) { Console.Error.WriteLine("Invalid argument: Base year expected"); return 1; } string bmin = clp.GetArgument(1).Trim().ToLowerInvariant(); DateTime time = Debase28Minutes(baseYear, bmin); if (time == DateTime.MinValue) { Console.Error.WriteLine("Invalid bmin value."); return 0; } Console.WriteLine(time.ToString("yyyy-MM-dd HH:mm") + " UTC"); Console.WriteLine(time.ToLocalTime().ToString("yyyy-MM-dd HH:mm K")); return 0; } if (clp.IsOptionSet("de-b36min")) { int baseYear; if (!int.TryParse(clp.GetArgument(0), out baseYear)) { Console.Error.WriteLine("Invalid argument: Base year expected"); return 1; } string bmin = clp.GetArgument(1).Trim().ToLowerInvariant(); DateTime time = Debase36Minutes(baseYear, bmin); if (time == DateTime.MinValue) { Console.Error.WriteLine("Invalid b36min value."); return 0; } Console.WriteLine(time.ToString("yyyy-MM-dd HH:mm") + " UTC"); Console.WriteLine(time.ToLocalTime().ToString("yyyy-MM-dd HH:mm K")); return 0; } if (clp.IsOptionSet("D")) { int baseYear; if (!int.TryParse(clp.GetArgument(0), out baseYear)) { Console.Error.WriteLine("Invalid argument: Base year expected"); return 1; } string dmin = clp.GetArgument(1).Trim(); DateTime time = DedecMinutes(baseYear, dmin); if (time == DateTime.MinValue) { Console.Error.WriteLine("Invalid dmin value."); return 0; } Console.WriteLine(time.ToString("yyyy-MM-dd HH:mm") + " UTC"); Console.WriteLine(time.ToLocalTime().ToString("yyyy-MM-dd HH:mm K")); return 0; } if (clp.IsOptionSet("x")) { int baseYear; if (!int.TryParse(clp.GetArgument(0), out baseYear)) { Console.Error.WriteLine("Invalid argument: Base year expected"); return 1; } revTime = DateTime.UtcNow; long ticks1min = TimeSpan.FromMinutes(1).Ticks; revTime = new DateTime(revTime.Ticks / ticks1min * ticks1min, DateTimeKind.Utc); for (int i = 0; i < 10; i++) { Console.WriteLine(revTime.ToLocalTime().ToString("yyyy-MM-dd HH:mm K") + " = " + HexMinutes(baseYear, 1)); revTime = revTime.AddMinutes(1); } return 0; } if (clp.IsOptionSet("b")) { int baseYear; if (!int.TryParse(clp.GetArgument(0), out baseYear)) { Console.Error.WriteLine("Invalid argument: Base year expected"); return 1; } revTime = DateTime.UtcNow; long ticks20min = TimeSpan.FromMinutes(20).Ticks; revTime = new DateTime(revTime.Ticks / ticks20min * ticks20min, DateTimeKind.Utc); for (int i = 0; i < 10; i++) { Console.WriteLine(revTime.ToLocalTime().ToString("yyyy-MM-dd HH:mm K") + " = " + Base28Minutes(baseYear, 1)); revTime = revTime.AddMinutes(20); } return 0; } if (clp.IsOptionSet("test-b36min")) { int baseYear; if (!int.TryParse(clp.GetArgument(0), out baseYear)) { Console.Error.WriteLine("Invalid argument: Base year expected"); return 1; } revTime = DateTime.UtcNow; long ticks10min = TimeSpan.FromMinutes(10).Ticks; revTime = new DateTime(revTime.Ticks / ticks10min * ticks10min, DateTimeKind.Utc); for (int i = 0; i < 10; i++) { Console.WriteLine(revTime.ToLocalTime().ToString("yyyy-MM-dd HH:mm K") + " = " + Base36Minutes(baseYear, 1)); revTime = revTime.AddMinutes(10); } return 0; } buildTime = DateTimeOffset.Now; bool patchAssemblyInfoFile = clp.IsOptionSet("a"); bool restoreAssemblyInfoFile = clp.IsOptionSet("s"); multiProjectMode = clp.IsOptionSet("m"); bool showRevision = clp.IsOptionSet("r"); bool stopIfModified = clp.IsOptionSet("M"); bool ignoreMissing = clp.IsOptionSet("i"); onlyInformationalVersion = clp.IsOptionSet("I"); string path = clp.GetArgument(0); string customFormat = "{!}{commit}"; if (clp.IsOptionSet("f")) customFormat = clp.GetOptionValue("f"); if (!patchAssemblyInfoFile && !restoreAssemblyInfoFile && !showRevision) showRevision = true; // Default action if (string.IsNullOrEmpty(path)) path = "."; if (debugOutput) Console.Error.WriteLine("Working on path " + path); bool hasProcessed = false; List<string> projectDirs = new List<string>(); if (multiProjectMode) { // Treat the single directory argument as the solution file name if (!path.ToLowerInvariant().EndsWith(".sln")) { Console.Error.WriteLine("Error: Specified file name is invalid. Only *.sln files accepted in\nmulti-project mode."); return 1; } if (!File.Exists(path)) { Console.Error.WriteLine("Error: Specified solution file does not exist."); return 1; } // Scan the solution file for projects and add them to the list string solutionDir = Path.GetDirectoryName(path); using (StreamReader sr = new StreamReader(path)) { while (!sr.EndOfStream) { string line = sr.ReadLine(); Match m = Regex.Match(line, @"^Project\(.+\) = "".+"", ""(.+\.(?:csproj|vbproj))"""); if (m.Success) { string projectPath = Path.Combine(solutionDir, m.Groups[1].Value); string projectDir = Path.GetDirectoryName(projectPath); if (debugOutput) Console.Error.WriteLine("Add project in " + projectDir); projectDirs.Add(projectDir); } } } if (projectDirs.Count == 0) { Console.Error.WriteLine("Error: Specified solution file contains no projects."); return 1; } // From now on, work with the solution directory as default path to get the revision of path = solutionDir; } if (patchAssemblyInfoFile) { if (!hasProcessed) { ProcessDirectory(path, ignoreMissing, true); if (revision == 0) { if (ignoreMissing) { revTime = DateTimeOffset.Now; } else { Console.Error.WriteLine("Error: Not a Subversion working directory."); return 1; } } hasProcessed = true; } if (stopIfModified && isModified) { Console.Error.WriteLine("Error: Subversion working directory contains uncommited changes, stop requested by option."); return 1; } if (multiProjectMode) { bool success = true; foreach (string projectDir in projectDirs) { success &= PatchAssemblyInfoFile(projectDir); } if (!success) { return 1; } } else { if (!PatchAssemblyInfoFile(path)) { return 1; } } } if (restoreAssemblyInfoFile) { if (multiProjectMode) { bool success = true; foreach (string projectDir in projectDirs) { success &= RestoreAssemblyInfoFile(projectDir); } if (!success) { return 1; } } else { if (!RestoreAssemblyInfoFile(path)) { return 1; } } } if (showRevision) { if (!hasProcessed) { ProcessDirectory(path, ignoreMissing, true); if (revision == 0) { if (ignoreMissing) { revTime = DateTimeOffset.Now; } else { Console.Error.WriteLine("Error: Not a Subversion working directory."); return 1; } } hasProcessed = true; } Console.WriteLine(ResolveFormat(customFormat)); } return 0; }
public void OldEraToLocalTime () { TimeSpan offset = TimeSpan.Zero; var dto = new DateTimeOffset (new DateTime (1900, 1, 1).Ticks, offset); // Should never throw dto.ToLocalTime (); }
public DateTimeOffset GetLastWriteTime(string path) { if (path == null) { throw new ArgumentNullException("path"); } if (path.Trim().Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), "path"); } if (this.m_bDisposed) { throw new ObjectDisposedException(null, Environment.GetResourceString("IsolatedStorage_StoreNotOpen")); } if (this.m_closed) { throw new InvalidOperationException(Environment.GetResourceString("IsolatedStorage_StoreNotOpen")); } this.m_fiop.Assert(); this.m_fiop.PermitOnly(); string str2 = LongPath.NormalizePath(this.GetFullPath(path)); try { Demand(new FileIOPermission(FileIOPermissionAccess.Read, new string[] { str2 }, false, false)); } catch { DateTimeOffset offset3 = new DateTimeOffset(0x641, 1, 1, 0, 0, 0, TimeSpan.Zero); return offset3.ToLocalTime(); } DateTimeOffset lastWriteTime = LongPathFile.GetLastWriteTime(str2); CodeAccessPermission.RevertAll(); return lastWriteTime; }