public static System.DateTime JsonToDateTime(string jsonDate) { string text = jsonDate.Substring(5, jsonDate.Length - 6) + "+0800"; System.DateTimeKind dateTimeKind = System.DateTimeKind.Utc; int num = text.IndexOf('+', 1); if (num == -1) { num = text.IndexOf('-', 1); } if (num != -1) { dateTimeKind = System.DateTimeKind.Local; text = text.Substring(0, num); } long num2 = long.Parse(text, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture); long ticks = new System.DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc).Ticks; System.DateTime dateTime = new System.DateTime(num2 * 10000L + ticks, System.DateTimeKind.Utc); System.DateTime result; switch (dateTimeKind) { case System.DateTimeKind.Unspecified: result = System.DateTime.SpecifyKind(dateTime.ToLocalTime(), System.DateTimeKind.Unspecified); return(result); case System.DateTimeKind.Local: result = dateTime.ToLocalTime(); return(result); } result = dateTime; return(result); }
public DateTime JsonToDateTime(string jsonDate) { string value = jsonDate.Substring(6, jsonDate.Length - 8); DateTimeKind kind = DateTimeKind.Utc; int index = value.IndexOf('+', 1); if (index == -1) index = value.IndexOf('-', 1); if (index != -1) { kind = DateTimeKind.Local; value = value.Substring(0, index); } long javaScriptTicks = long.Parse(value, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture); long InitialJavaScriptDateTicks = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Ticks; DateTime utcDateTime = new DateTime((javaScriptTicks * 10000) + InitialJavaScriptDateTicks, DateTimeKind.Utc); DateTime dateTime; switch (kind) { case DateTimeKind.Unspecified: dateTime = DateTime.SpecifyKind(utcDateTime.ToLocalTime(), DateTimeKind.Unspecified); break; case DateTimeKind.Local: dateTime = utcDateTime.ToLocalTime(); break; default: dateTime = utcDateTime; break; } return dateTime; }
public void DateTimeKindHandling() { DateTime value = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); MemoryStream ms = new MemoryStream(); BsonWriter writer = new BsonWriter(ms); writer.WriteStartObject(); writer.WritePropertyName("DateTime"); writer.WriteValue(value); writer.WriteEndObject(); byte[] bson = ms.ToArray(); JObject o; BsonReader reader; reader = new BsonReader(new MemoryStream(bson), false, DateTimeKind.Utc); o = (JObject)JToken.ReadFrom(reader); Assert.AreEqual(value, (DateTime)o["DateTime"]); reader = new BsonReader(new MemoryStream(bson), false, DateTimeKind.Local); o = (JObject)JToken.ReadFrom(reader); Assert.AreEqual(value.ToLocalTime(), (DateTime)o["DateTime"]); reader = new BsonReader(new MemoryStream(bson), false, DateTimeKind.Unspecified); o = (JObject)JToken.ReadFrom(reader); Assert.AreEqual(DateTime.SpecifyKind(value.ToLocalTime(), DateTimeKind.Unspecified), (DateTime)o["DateTime"]); }
public static string ExchangeKmhInOrders(List<Guid> orderArticles, DateTime timeStamp, Guid prodNomenId, TechnDatesSpeciality speciality) { using (ProductProvider provider = new ProductProvider()) { var dates = from date in provider.TechnDates where orderArticles.Contains(date.OrderArticleID) && date._dictNomenID == prodNomenId select date; foreach (var date in dates) { switch (speciality) { case TechnDatesSpeciality.Main: date.gen_date = timeStamp.ToLocalTime(); break; case TechnDatesSpeciality.Svar: date.svar_date = timeStamp.ToLocalTime(); break; case TechnDatesSpeciality.Him: date.him_date = timeStamp.ToLocalTime(); break; case TechnDatesSpeciality.Techn: date.techn_date = timeStamp.ToLocalTime(); break; } } provider.SubmitChanges(); } return new PostResult("Ok", 0).ToString(); }
public void ChangeDSTFromWinterToSummerToWinter() { var dateTime = new DateTime(2015, 10, 25, 1, 30, 0, DateTimeKind.Utc); var timeInput = new CnDTimeInput(); timeInput.SelectedDateTime = dateTime.ToLocalTime(); Assert.That(timeInput.IsSummerPeriod, Is.EqualTo(false)); timeInput.SelectedDateTime = dateTime.AddHours(-1).ToLocalTime(); Assert.That(timeInput.IsSummerPeriod, Is.EqualTo(true)); timeInput.SelectedDateTime = dateTime.ToLocalTime(); Assert.That(timeInput.IsSummerPeriod, Is.EqualTo(false)); }
/// <summary> /// Adds a tooltip to a Steam mod showing its update status. /// </summary> /// <param name="tooltip">The tooltip under construction.</param> /// <param name="modUpdate">The mod update executor which can update this mod.</param> /// <param name="localDate">The local last update date.</param> /// <param name="updButton">The button to be used for updating this mod.</param> /// <returns>The status of the Steam mod.</returns> private static ModStatus AddSteamUpdate(StringBuilder tooltip, ModToUpdate modUpdate, System.DateTime localDate, PButton updButton) { var steamDate = modUpdate.LastSteamUpdate; var updated = ModStatus.Disabled; if (steamDate > System.DateTime.MinValue) { // Generate tooltip for mod's current date and last Steam update var ours = ModUpdateInfo.FindModInConfig(modUpdate.SteamID.m_PublishedFileId); var ourDate = System.DateTime.MinValue; var globalDate = modUpdate.LastSteamUpdate; // Do we have a better estimate? if (ours != null) { ourDate = new System.DateTime(ours.LastUpdated, DateTimeKind.Utc); } // Allow some time for download delays etc if (localDate.AddMinutes(UPDATE_JITTER) >= globalDate) { tooltip.Append(ModUpdateDateStrings.MOD_UPDATED); updated = ModStatus.UpToDate; } else if (ourDate.AddMinutes(UPDATE_JITTER) >= globalDate) { tooltip.Append(ModUpdateDateStrings.MOD_UPDATED_BYUS); localDate = ourDate; updated = ModStatus.UpToDateLocal; } else { tooltip.Append(ModUpdateDateStrings.MOD_OUTDATED); updated = ModStatus.Outdated; } // AppendLine appends platform specific separator tooltip.Append("\n"); tooltip.AppendFormat(ModUpdateDateStrings.LOCAL_UPDATE, localDate. ToLocalTime()); tooltip.Append("\n"); tooltip.AppendFormat(ModUpdateDateStrings.STEAM_UPDATE, globalDate. ToLocalTime()); updButton.OnClick = new ModUpdateTask(modUpdate).TryUpdateMods; } else { // Steam update could not be determined tooltip.AppendFormat(ModUpdateDateStrings.LOCAL_UPDATE, localDate. ToLocalTime()); tooltip.Append("\n"); tooltip.AppendFormat(ModUpdateDateStrings.STEAM_UPDATE_UNKNOWN); } return(updated); }
public void StartSession(InstalledGame game, DateTime startDateTime) { Icon = game.Icon; TabText = game.Name; CloseButton = false; CloseButtonVisible = false; this.pictureBoxArt.Image = game.Image; this.labelGameName.Text = game.Name; this.labelStartedPlaying.Text = string.Format ("Started playing on {0} at {1}", startDateTime.ToLocalTime().ToShortDateString (), startDateTime.ToLocalTime().ToShortTimeString ()); this.labelIdle.Text = ""; }
void DisplayDateTimeFullInfo(System.DateTime dateTime, string title) { MessageBox.Show(title + Environment.NewLine + " ToString()=" + dateTime.ToString() + Environment.NewLine + " ToShortDateString()=" + dateTime.ToShortDateString() + Environment.NewLine + " ToShortTimeString()=" + dateTime.ToShortTimeString() + Environment.NewLine //+ " ToLongTimeString()=" + dateTime.ToLongTimeString() + Environment.NewLine + " ToUniversalTime().ToString()=" + dateTime.ToUniversalTime().ToString() + Environment.NewLine + " ToLocalTime().ToString()=" + dateTime.ToLocalTime().ToString() + Environment.NewLine + " ToUniversalTime().ToLocalTime().ToString()=" + dateTime.ToUniversalTime().ToLocalTime().ToString() + Environment.NewLine + " ToLocalTime().ToUniversalTime().ToString()=" + dateTime.ToLocalTime().ToUniversalTime() + Environment.NewLine + " Hours=" + dateTime.Hour.ToString() + Environment.NewLine + " Minutes=" + dateTime.Minute.ToString() + Environment.NewLine + " Seconds=" + dateTime.Second.ToString() + Environment.NewLine ); }
//Code PES private string GetBuildNumber() { string strBuildNumber = string.Empty, timestamp = string.Empty; string filePath = System.Reflection.Assembly.GetCallingAssembly().Location; const int c_PeHeaderOffset = 60; const int c_LinkerTimestampOffset = 8; byte[] b = new byte[2048]; System.IO.Stream 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(); } } int i = System.BitConverter.ToInt32(b, c_PeHeaderOffset); int secondsSince1970 = System.BitConverter.ToInt32(b, i + c_LinkerTimestampOffset); DateTime dtDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); dtDate = dtDate.AddSeconds(secondsSince1970); dtDate = dtDate.ToLocalTime(); timestamp = dtDate.ToString("yyyyMMddHHmmss"); if (timestamp == string.Empty) { timestamp = "UNKOWN!"; } strBuildNumber = "Build : " + timestamp; return strBuildNumber; }
/// <summary> /// DateTime时间格式转换为Unix时间戳格式 /// </summary> /// <param name="time"> DateTime时间格式</param> /// <returns>Unix时间戳格式</returns> public static int convertDateTime2TimeStamp(System.DateTime time) { DateTime endTime = time.ToLocalTime(); DateTime startTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).ToLocalTime(); return((int)(endTime - startTime).TotalSeconds); }
private static DateTime RetrieveLinkerTimestamp() { string filePath = System.Reflection.Assembly.GetCallingAssembly().Location; const int c_PeHeaderOffset = 60; const int c_LinkerTimestampOffset = 8; byte[] b = new byte[2048]; System.IO.Stream 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(); } } int i = System.BitConverter.ToInt32(b, c_PeHeaderOffset); int secondsSince1970 = System.BitConverter.ToInt32(b, i + c_LinkerTimestampOffset); DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); dt = dt.AddSeconds(secondsSince1970); dt = dt.ToLocalTime(); return dt; }
// USERGUIDEACTION INTERFACE protected override bool OnExecute() { if (base.OnExecute() == false) { return(false); } PlayerPersistantInfo ppi = PPIManager.Instance.GetLocalPPI(); BanInfo baninfo = ppi != null ? ppi.Ban : default(BanInfo); System.DateTime date = new System.DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc) + System.TimeSpan.FromMilliseconds(baninfo.EndTime); if (date < CloudDateTime.UtcNow) { return(false); } ShowPopup().SetData(date.ToLocalTime(), baninfo.Message); // don't allow user to go through // there is only one way out // and it's logout ... return(true); }
private static string datify(int timestamp) { System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); dateTime = dateTime.AddSeconds(timestamp); dateTime = dateTime.ToLocalTime(); return(dateTime.ToString()); }
public static DateTime GetBulidTime() { var filePath = System.Reflection.Assembly.GetCallingAssembly().Location; const int cPeHeaderOffset = 60; const int cLinkerTimestampOffset = 8; var b = new byte[2048]; System.IO.Stream 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 i = BitConverter.ToInt32(b, cPeHeaderOffset); var secondsSince1970 = BitConverter.ToInt32(b, i + cLinkerTimestampOffset); var dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); dt = dt.AddSeconds(secondsSince1970); dt = dt.ToLocalTime(); return dt; }
public void DisplayExpiredLicenseError(DateTime expirationDate) { errorPanel.Visible = true; errorMessageLabel.Text = "The license file you have selected is expired."; selectedFileExpirationDateLabel.Text = String.Format("Expiration Date: {0}", expirationDate.ToLocalTime().ToShortDateString()); Height = 376; }
public TimePicker() { InitializeComponent(); this.DataContext = this; CurrentTime = new DateTime(2015, 12, 30, 13, 30, 00); SelectedTime = CurrentTime.ToLocalTime().ToString("t"); }
public void SaveDateTimeToDatabase() { var dbFactory = new OrmLiteConnectionFactory(base.ConnectionString, SqlServerOrmLiteDialectProvider.Instance); SqlServerOrmLiteDialectProvider.Instance.EnsureUtc(true); using (var db = dbFactory.OpenDbConnection()) { var dateTime = new DateTime(2012, 1, 1, 1, 1, 1, DateTimeKind.Local); var x = InsertAndSelectDateTime(db, dateTime); Assert.AreEqual(DateTimeKind.Utc, x.Test.Kind); Assert.AreEqual(x.Test.ToUniversalTime(), dateTime.ToUniversalTime()); Assert.AreEqual(x.Test.ToLocalTime(), dateTime.ToLocalTime()); dateTime = new DateTime(2012, 1, 1, 1, 1, 1, DateTimeKind.Utc); x = InsertAndSelectDateTime(db, dateTime); Assert.AreEqual(DateTimeKind.Utc, x.Test.Kind); Assert.AreEqual(x.Test.ToUniversalTime(), dateTime.ToUniversalTime()); Assert.AreEqual(x.Test.ToLocalTime(), dateTime.ToLocalTime()); dateTime = new DateTime(2012, 1, 1, 1, 1, 1, DateTimeKind.Unspecified); x = InsertAndSelectDateTime(db, dateTime); Assert.AreEqual(DateTimeKind.Utc, x.Test.Kind); Assert.AreEqual(x.Test.ToUniversalTime(), dateTime); Assert.AreEqual(x.Test.ToLocalTime(), dateTime.ToLocalTime()); } }
/// <summary> /// Parse the given string representation into a <see cref="DateTime"/> value. /// </summary> /// <param name="value">A string representation of a date time.</param> /// <returns>A <see cref="DateTime"/> value.</returns> public DateTime ParseDateTime(string value) { int year, month, day, hour, minute, second, offsetHours, offsetMinutes; long ticks; DateTimeKind dateTimeKind; GetDateTimeComponents(value, out year, out month, out day, out hour, out minute, out second, out ticks, out offsetHours, out offsetMinutes, out dateTimeKind); var toLocal = false; if (dateTimeKind == DateTimeKind.Local) { hour -= offsetHours; minute -= offsetMinutes; Adjust(ref year, ref month, ref day, ref hour, ref minute); dateTimeKind = DateTimeKind.Utc; toLocal = true; } var dateTime = new DateTime(year, month, day, hour, minute, second, dateTimeKind); dateTime = dateTime.AddTicks(ticks); if (toLocal) { dateTime = dateTime.ToLocalTime(); } return dateTime; }
private string getDescriptionForTime(DateTime startTime) { if (startTime < DateTime.UtcNow) return "On Now"; return "Starting at " + startTime.ToLocalTime().ToShortTimeString(); }
public Form1() { _heartbeat = 0; InitializeComponent(); this.WindowState = FormWindowState.Minimized; icnStopped = Resources.Icon1; icnStarted = Resources.Icon2; timestamp = Utils.RetrieveLinkerTimestamp(); // notifyIcon1.Text = "MTC Multi-SHDR Agent - Release " + _assembly.ImageRuntimeVersion ; notifyIcon1.Text = "Autostart MTC SHDR Agent - Release " + timestamp.ToLocalTime(); ; notifyIcon1.Icon = icnStopped; Utilities.Logger.RestartLog(); aTimer = new System.Timers.Timer(); aTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent); // System.Threading.Thread.Sleep(30000); MTConnectAgentCore.Configuration.defaultDirectory = Application.StartupPath + "\\"; MTConnectAgentCore.Configuration.confDirectory = "" ; SystemEvents.SessionEnding += SystemEvents_SessionEnding; Reset(); }
// 按照时间单位,把时间值零头去除,正规化,便于后面计算差额 /// <summary> /// 按照时间基本单位,去掉零头,便于互相计算(整单位的)差额。 /// 算法是先转换为本地时间,去掉零头,再转换回 GMT 时间 /// </summary> /// <param name="strUnit">时间单位。day/hour之一。如果为空,相当于 day</param> /// <param name="time">要处理的时间。为 GMT 时间</param> /// <param name="strError">返回出错信息</param> /// <returns>-1: 出错; 0: 成功</returns> public static int RoundTime(string strUnit, ref DateTime time, out string strError) { strError = ""; time = time.ToLocalTime(); if (strUnit == "day" || string.IsNullOrEmpty(strUnit) == true) { time = new DateTime(time.Year, time.Month, time.Day, 12, 0, 0, 0); } else if (strUnit == "hour") { time = new DateTime(time.Year, time.Month, time.Day, time.Hour, 0, 0, 0); } else { strError = "未知的时间单位 '" + strUnit + "'"; return -1; } time = time.ToUniversalTime(); return 0; }
public static void Create() { stopwatch = Stopwatch.StartNew(); startUtc = DateTime.UtcNow; start = startUtc.ToLocalTime(); stamp = Statistics.Start.ToString(Const.StampFormat, CultureInfo.InvariantCulture); }
private static DateTime UnixTimeStampToDateTime(long unixTimeStamp) { DateTime dtDateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); dtDateTime = dtDateTime.AddSeconds(unixTimeStamp); return(dtDateTime.ToLocalTime()); }
//Assumes the datastream is setup public async Task GetData(HashSet<IKey> keys, DateTime dtbegin, DateTime dtend, String outputFileName) { if (datastream == null) return; FileStream fs = new FileStream(outputFileName, FileMode.Append); StreamWriter swOut = new StreamWriter(fs); DateTime dtbeginutc = dtbegin.ToUniversalTime(); DateTime dtendutc = dtend.ToUniversalTime(); foreach (IKey key in keys) { IEnumerable<IDataItem> dataItemEnum = await Task.Run(() => datastream.GetAll(key, dtbeginutc.Ticks, dtendutc.Ticks)); if (dataItemEnum != null) { foreach (IDataItem di in dataItemEnum) { DateTime ts = new DateTime(di.GetTimestamp()); swOut.WriteLine(key + ", " + ts.ToLocalTime() + ", " + di.GetVal().ToString()); } } } swOut.Close(); }
public CandidateViewModel(CandidateUserModel candidate, string name, string email, DateTime modificationDate) { Candidate = candidate; Name = name; Email = email; ModificationDate = modificationDate.ToLocalTime(); }
public static DateTime ConvertTicksToDateTime(long ticks) { var date = new DateTime(1970, 1, 1); date = date.AddSeconds(ticks); return date.ToLocalTime(); }
//#endif public static int dateTimeToUnixTime(System.DateTime dt) { var date = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); var unixTimestamp = System.Convert.ToInt32((dt - date.ToLocalTime()).TotalSeconds); return(unixTimestamp); }
public static DateTime ApplicationLastUpdate() { #region Variable string filePath = System.Reflection.Assembly.GetCallingAssembly().Location; const int c_PeHeaderOffset = 60; const int c_LinkerTimestampOffset = 8; byte[] b = new byte[2048]; System.IO.Stream s = null; DateTime dttm = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); #endregion #region Procedure 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(); } } int i = System.BitConverter.ToInt32(b, c_PeHeaderOffset); int secondsSince1970 = System.BitConverter.ToInt32(b, i + c_LinkerTimestampOffset); dttm = dttm.AddSeconds(secondsSince1970); dttm = dttm.ToLocalTime(); #endregion return dttm; }
public void datetime_kind_can_change_based_on_usage() { var originalDate = new DateTime(2012, 7, 1, 12, 0, 0); // An unspecified time can be change to a local time. .NET // will assume that the original value was universal. var local = originalDate.ToLocalTime(); Assert.AreNotEqual(originalDate, local); Assert.AreEqual(DateTimeKind.Local, local.Kind); Assert.AreEqual(originalDate.AddHours(-4), local); Assert.AreEqual(DateTimeKind.Unspecified, originalDate.Kind); // An unspecified time can be change to a universal time. .NET // will assume that the original value was local. var utc = originalDate.ToUniversalTime(); Assert.AreNotEqual(originalDate, utc); Assert.AreEqual(DateTimeKind.Utc, utc.Kind); Assert.AreEqual(originalDate.AddHours(4), utc); Assert.AreEqual(DateTimeKind.Unspecified, originalDate.Kind); // So, according to .NET, 2 AM GMT and 2 AM in the current time // zone are the same thing. Pay no attention that they're different // by 4 hours (or 5 in the winter)! var utc2am = new DateTime(2012, 9, 26, 2, 0, 0, DateTimeKind.Utc); var local2am = new DateTime(2012, 9, 26, 2, 0, 0, DateTimeKind.Local); Assert.AreEqual(utc2am, local2am); }
public static DateTime FromUnixTime(this long seconds) { var time = new DateTime(1970, 1, 1); time = time.AddSeconds(seconds); return time.ToLocalTime(); }
public override object DeserializeObject(object value, Type type) { bool isString = value is string; Type valueType = null; bool isEnum = type.IsEnum || (IsNullable(type, out valueType) && valueType.IsEnum); if (isEnum && (isString || value is Int32 || value is Int64)) { if (!isString || Enum.IsDefined(valueType ?? type, value)) { return Enum.Parse(valueType ?? type, value.ToString()); } } else if (type == typeof(DateTime)) { var s = value as string; if (s != null && s.StartsWith("/Date(", StringComparison.Ordinal) && s.EndsWith(")/", StringComparison.Ordinal)) { int tzCharIndex = s.IndexOfAny(new char[] { '+', '-' }, 7); long javaScriptTicks = Convert.ToInt64(s.Substring(6, (tzCharIndex > 0) ? tzCharIndex - 6 : s.Length - 8)); DateTime time = new DateTime((javaScriptTicks * 10000) + _initialJavaScriptDateTicks, DateTimeKind.Utc); if (tzCharIndex > 0) { time = time.ToLocalTime(); } return time; } } return base.DeserializeObject(value, type); }
/// <summary> /// Create a new instance of LiveStream. /// </summary> /// <param name="channel">The channel being streamed.</param> /// <param name="rtspUrl">The rtsp URL to the stream.</param> /// <param name="streamStartedTimeUtc">The date and time the stream was first started.</param> public LiveStream(Channel channel, string rtspUrl, DateTime streamStartedTimeUtc) { this.Channel = channel; this.RtspUrl = rtspUrl; this.StreamStartedTime = streamStartedTimeUtc.ToLocalTime(); this.StreamLastAliveTimeUtc = streamStartedTimeUtc; }
public TimeSpan GetNextInterval(DateTime lastSchedule, bool ignoreMissed = false) { DateTime now = _dateTimeNowProvider.Now; lastSchedule = lastSchedule == DateTime.MinValue ? now : lastSchedule.ToLocalTime(); // Check for next occurence from last occurence DateTime nextOccurrence = _crontabSchedule.GetNextOccurrence(lastSchedule); // If next occurence is in the future use it if (nextOccurrence >= now) { return nextOccurrence - now; } // Otherwise if next occurence is up to 10 minutes in the past or ignore missed is true use now if (ignoreMissed || nextOccurrence >= now - TimeSpan.FromMinutes(10)) { return TimeSpan.Zero; } var nextOccurrences = _crontabSchedule.GetNextOccurrences(lastSchedule, now); int nextOccurrencesCount = nextOccurrences.Count(); if (nextOccurrencesCount > 0) { _logger.LogWarning("Missed {0} schedules, most recent at {1}".FormatCurrentCulture(nextOccurrencesCount, nextOccurrences.Last())); } // Return next occurence after now return _crontabSchedule.GetNextOccurrence(now) - now; }
public static string formatTimestamp(long timestamp) { DateTime date = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); date = date.AddMilliseconds(timestamp); return(date.ToLocalTime().ToString("T")); }
public override String ConvertFromDate(DateTime value) { value = value.ToLocalTime(); var date = String.Format(CultureInfo.InvariantCulture, "{0:0000}-{1:00}-{2:00}", value.Year, value.Month, value.Day); var time = String.Format(CultureInfo.InvariantCulture, "{0:00}:{1:00}:{2:00},{3:000}", value.Hour, value.Minute, value.Second, value.Millisecond); return String.Concat(date, "T", time); }
public void SetData(byte[] data, int index, int count) { using (MemoryStream stream = new MemoryStream(data, index, count, false)) { using (ZipHelperStream stream2 = new ZipHelperStream(stream)) { int num; DateTime time; this._flags = (Flags) ((byte) stream2.ReadByte()); if ((((byte) (this._flags & Flags.ModificationTime)) != 0) && (count >= 5)) { num = stream2.ReadLEInt(); time = new DateTime(0x7b2, 1, 1, 0, 0, 0); time = time.ToUniversalTime() + new TimeSpan(0, 0, 0, num, 0); this._modificationTime = time.ToLocalTime(); } if (((byte) (this._flags & Flags.AccessTime)) != 0) { num = stream2.ReadLEInt(); time = new DateTime(0x7b2, 1, 1, 0, 0, 0); time = time.ToUniversalTime() + new TimeSpan(0, 0, 0, num, 0); this._lastAccessTime = time.ToLocalTime(); } if (((byte) (this._flags & Flags.CreateTime)) != 0) { num = stream2.ReadLEInt(); time = new DateTime(0x7b2, 1, 1, 0, 0, 0); this._createTime = (time.ToUniversalTime() + new TimeSpan(0, 0, 0, num, 0)).ToLocalTime(); } } } }
public static DateTime ToDateTime(this long value) { DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); dateTime = dateTime.AddSeconds(value); return dateTime.ToLocalTime(); }
public void FunctionWithDateTime() { var dateTime = new DateTime(2013, 1, 1, 12, 13, 14); var result = _client.ExecuteFunctionAsScalar<DateTime>("PassThroughDateTime", new Entry() { { "dateTime", dateTime } }); Assert.Equal(dateTime.ToLocalTime(), result); }
public DatePosted ParsePostedDate(DateTime date) { long seconds; long minutes; long days; long hours; var datePosted = new DatePosted() {OriginalPostedDate = date}; var totalSeconds = DateTime.Now.ToLocalTime() .Subtract(date.ToLocalTime()) .TotalSeconds; var parsedSeconds = Math.Abs((long) totalSeconds); var totalMinutes = DivideWithRemainder(parsedSeconds, NumberOfSecondsOrMinutes, out seconds); var totalHours = DivideWithRemainder(totalMinutes, NumberOfSecondsOrMinutes, out minutes); var totalDays = DivideWithRemainder(totalHours, NumberOfHoursInOneDay, out hours); var weeks = DivideWithRemainder(totalDays, NumberOfDaysInAWeek, out days); datePosted.SecondsFromPostedDate = parsedSeconds; datePosted.SecondsFromPostedDate = seconds; datePosted.MinutesFromPostedDate = minutes; datePosted.HoursFromPostedDate = hours; datePosted.DaysFromPostedDate = days; datePosted.WeeksFromPostedDate = weeks; return datePosted; }
static public string GetTimeSince2009(UInt32 second) { System.DateTime baseDate = new System.DateTime(2009, 1, 1); baseDate = baseDate.AddSeconds(second); // 调整为当前系统时区 baseDate = baseDate.ToLocalTime(); return(baseDate.ToString("yyyy-MM-dd-hh:mm")); }
//消息提示框添加信息 public void addListItemText(string msg) { logCount++; WriteLog(msg); //Console.Write("{0}\n",msg); System.DateTime now = System.DateTime.Now; this.log.AppendText(logCount.ToString() + " " + now.ToLocalTime().ToString() + ": " + msg + "\n"); }
/// <summary> /// Changes downloaded unix timestamp to date format /// </summary> /// <returns>String with a proper date and hour</returns> public string GetDateTime() { DateTime localDateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); // creating a new DateTime object localDateTime = localDateTime.AddSeconds(timestamp); // adding downloaded timestamp to object return(localDateTime.ToLocalTime().ToString("yyyy-MM-dd, HH:mm:ss ")); // creating string based on DateTime class with given format }
//automate the time stamping. Slight loss of precision is possible (but unlikely). public void markEvent(string str) { long fTest = stopWatch.ElapsedTicks; System.DateTime dt = DateTime.Now; dt = dt.ToLocalTime(); write(str + " " + "default" + " " + dt.ToString("yyyy-MM-dd HH:mm:ss.ffffff") + " " + fTest.ToString() + "\n"); }
public System.DateTime ConvertTimeStampToDateTime(double timestamp) { //create a new datetime value based on the unix epoch System.DateTime converted = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); //add the timestamp to the value System.DateTime newdatetime = converted.AddSeconds(timestamp); //return the value in string format return(newdatetime.ToLocalTime()); }
public static string GetStringFromDate(System.DateTime unespecifiedDate) { if (unespecifiedDate.Kind.Equals(DateTimeKind.Local)) { return(unespecifiedDate.ToLocalTime().ToString("d")); } System.DateTime localDateTime = System.TimeZoneInfo.ConvertTimeFromUtc(unespecifiedDate.ToUniversalTime(), TimeZoneInfo.Local); return(localDateTime.ToLocalTime().ToString("d")); }
DateTime ParseDateTime(string logLine) { string[] tmp = logLine.Split(','); if (tmp[0] == "timestamp") { return(DateTime.MinValue); } System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); dateTime = dateTime.AddSeconds(Convert.ToUInt32(tmp[0])); return(dateTime.ToLocalTime()); }
public static int GetNowDayCode() { System.DateTime time = System.DateTime.Now; string str = string.Empty; time = time.ToLocalTime(); str = time.ToString("yyyyMMdd"); int timeValue = int.Parse(str); return(timeValue); }
public static double ConvertDateTimeToTimestamp(System.DateTime dateTime, bool isLocalTime) { double timestamp = 0; System.DateTime startTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); if (isLocalTime == false) { dateTime = dateTime.ToLocalTime(); } timestamp = (dateTime - startTime.ToLocalTime()).TotalSeconds; return(timestamp); }
//Load the current data of all the worlds public void LoadWorlds() { arcadeData.ReadData(); worlds = new List <World>(ArcadeData.instance.worldData.worlds); //If for some reason there's no data, instance worlds. //This should ONLY happen the first time you boot up the game. if (worlds.Count < 1) { for (int i = 0; i < 7; i++) { worlds.Add(new World()); handler.NewSeed(); worlds[i].seed = handler.rand_seed; worlds[i] = GenerateWorld(); } } UpdateWorlds(); System.DateTime nextWorld = new System.DateTime( arcadeData.worldData.nextWorld[0], arcadeData.worldData.nextWorld[1], arcadeData.worldData.nextWorld[2], arcadeData.worldData.nextWorld[3], arcadeData.worldData.nextWorld[4], arcadeData.worldData.nextWorld[5] ); Debug.Log(nextWorld); if (System.DateTime.Now > nextWorld) { Debug.Log("New World"); AddWorld(); } if (isMenu == true) { for (int i = 0; i < worlds.Count; i++) { DisplayWorld(i); } nextWorldText.text = "The next world will arrive at: " + nextWorld.ToLocalTime() + " GMT+00"; } if (isMenu == false) { StartLevel(); } }
public static string SecondToStringYMDLocal(int second) { System.DateTime time = new System.DateTime((long)second * 10000000 + 621355968000000000); string str = string.Empty; //str = time.ToString("yyyy/MM/dd HH:mm"); //long curTime = DateTime.UtcNow.Ticks - 621355968000000000; //string str2 = curTime.ToString("yyyy/MM/dd HH:mm"); //string str3 = GameTime.SecondToDate((long)second,true); time = time.ToLocalTime(); str = time.ToString("yyyy/MM/dd HH:mm"); return(str); }
/// <summary> /// Function that can be used to convert from a UnixTimeStamp (=seconds since 1 jan 1970) to a string in the format "yyyy-MM-dd HH:mm:ss". /// </summary> /// <param name="UnixTimestamp">UnixTimeStamp (integer, seconds) to convert to local time.</param> /// <returns>A string with the UnixTimeStamp in the format "yyyy-MM-dd HH:mm:ss".</returns> private static string ConvertUnixToLocalTimeStamp(int UnixTimestamp) { // First make a System.DateTime equivalent to the UNIX Epoch. System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); // Add the number of seconds in UNIX timestamp to be converted. dateTime = dateTime.AddSeconds(UnixTimestamp); dateTime = dateTime.ToLocalTime(); // The dateTime now contains the right date/time so to format the string, // use the standard formatting methods of the DateTime object. //dateTime.ToString( return(dateTime.ToString("yyyy-MM-dd HH:mm:ss")); }
public bool DownloadWeatherData(string city_name) { WebClient wc = new WebClient(); string jsonFile = ""; string icon_name; try { jsonFile = wc.DownloadString("https://api.openweathermap.org/data/2.5/weather?q=" + city_name + "&APPID=6d3a41189563209a62df88fc160e27eb"); // copying website's json content to a string dynamic stuff = JsonConvert.DeserializeObject(jsonFile); Coords.Longitude = (double)stuff.coord.lon; Coords.Latitude = (double)stuff.coord.lat; Temp = ((int)stuff.main.temp - 273).ToString() + " °C"; Pressure = (string)stuff.main.pressure + " hPa"; Humidity = (string)stuff.main.humidity + " %"; Name = city_name.ToUpper(); Status = (string)stuff.weather[0].main; Wind_Speed = ((double)stuff.wind.speed * 3.6).ToString() + " km/h"; Wind_Deg = (double)stuff.wind.deg; Country = (string)stuff.sys.country; DateTime sunriseDateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); sunriseDateTime = sunriseDateTime.AddSeconds((int)stuff.sys.sunrise); Sunrise = sunriseDateTime.ToLocalTime().ToString("dddd, HH:mm"); DateTime sunsetDateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); sunsetDateTime = sunsetDateTime.AddSeconds((int)stuff.sys.sunset); Sunset = sunsetDateTime.ToLocalTime().ToString("dddd, HH:mm"); DateTime DateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); DateTime = DateTime.AddSeconds((int)stuff.dt); Time = DateTime.ToLocalTime().ToString("dddd, HH:mm"); icon_name = (string)stuff.weather[0].icon; var fullFilePath = @"https://openweathermap.org/img/w/" + icon_name + ".png"; Imag = new BitmapImage(); Imag.BeginInit(); Imag.UriSource = new Uri(fullFilePath, UriKind.Absolute); Imag.EndInit(); return(true); } catch (WebException) { return(false); } }
static public string GetTimeSince1970(UInt32 second, out UInt32 year, out UInt32 month, out UInt32 day, out UInt32 hour, out UInt32 min) { System.DateTime baseDate = new System.DateTime(1970, 1, 1); baseDate = baseDate.AddSeconds(second); // 调整为当前系统时区 baseDate = baseDate.ToLocalTime(); year = (UInt32)baseDate.Year; month = (UInt32)baseDate.Month; day = (UInt32)baseDate.Day; hour = (UInt32)baseDate.Hour; min = (UInt32)baseDate.Minute; return(baseDate.ToString("yyyy-MM-dd-hh:mm")); }
static StackObject *ToLocalTime_19(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject *ptr_of_this_method; StackObject *__ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); System.DateTime instance_of_this_method = (System.DateTime) typeof(System.DateTime).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); var result_of_this_method = instance_of_this_method.ToLocalTime(); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method)); }
private object DeserializeStringIntoDateTime() { Match match = Regex.Match(this._s.ToString(), "^\"\\\\/Date\\((?<ticks>-?[0-9]+)(?:[a-zA-Z]|(?:\\+|-)[0-9]{4})?\\)\\\\/\""); string value = match.Groups["ticks"].Value; long num; object result; if (long.TryParse(value, out num)) { this._s.MoveNext(match.Length); System.DateTime dateTime = new System.DateTime(num * 10000L + JavaScriptSerializer.DatetimeMinTimeTicks, System.DateTimeKind.Utc); dateTime = dateTime.ToLocalTime(); result = dateTime; } else { result = this.DeserializeString(); } return(result); }
/// <summary> /// Adds a tooltip to a Steam mod showing its update status. /// </summary> /// <param name="tooltip">The tooltip under construction.</param> /// <param name="modUpdate">The mod update executor which can update this mod.</param> /// <param name="localDate">The local last update date.</param> /// <param name="updButton">The button to be used for updating this mod.</param> /// <param name="autoUpdate">Whether automatic updates are enabled.</param> /// <returns>The status of the Steam mod.</returns> private static ModStatus AddSteamUpdate(StringBuilder tooltip, ModToUpdate modUpdate, System.DateTime localDate, PButton updButton, bool autoUpdate) { var steamDate = modUpdate.LastSteamUpdate; var updated = GetModStatus(modUpdate, ref localDate); // Generate tooltip for mod's current date and last Steam update switch (updated) { case ModStatus.UpToDate: tooltip.Append(UISTRINGS.MOD_UPDATED); break; case ModStatus.UpToDateLocal: tooltip.Append(UISTRINGS.MOD_UPDATED_BYUS); break; case ModStatus.Outdated: tooltip.Append(autoUpdate ? UISTRINGS.MOD_ERR_UPDATE : UISTRINGS.MOD_OUTDATED); break; default: break; } // AppendLine appends platform specific separator tooltip.Append("\n"); tooltip.AppendFormat(cultureInfo, UISTRINGS.LOCAL_UPDATE, localDate.ToLocalTime()); tooltip.Append("\n"); if (updated == ModStatus.Disabled) { tooltip.AppendFormat(UISTRINGS.STEAM_UPDATE_UNKNOWN); } else { tooltip.AppendFormat(cultureInfo, UISTRINGS.STEAM_UPDATE, steamDate. ToLocalTime()); updButton.OnClick = new ModUpdateTask(modUpdate).TryUpdateMods; } return(updated); }
private void updateSatelliteTime(string timeWord) { if (timeWord != "") { // Extract hours, minutes, seconds and milliseconds int UtcHours = Convert.ToInt32(timeWord.Substring(0, 2)); int UtcMinutes = Convert.ToInt32(timeWord.Substring(2, 2)); int UtcSeconds = Convert.ToInt32(timeWord.Substring(4, 2)); int UtcMilliseconds = 0; // Extract milliseconds if it is available if (timeWord.Length > 7) { UtcMilliseconds = Convert.ToInt32(timeWord.Substring(7)); } // Now build a DateTime object with all values System.DateTime Today = System.DateTime.Now.ToUniversalTime(); System.DateTime SatelliteTime = new System.DateTime(Today.Year, Today.Month, Today.Day, UtcHours, UtcMinutes, UtcSeconds, UtcMilliseconds); RecivedData.SatelliteTime = SatelliteTime.ToLocalTime(); } }
public int TimeToMinute(System.DateTime dt, bool withTimezone) { int time; if (timezone == 99 || !withTimezone) { dt = dt.ToLocalTime(); return(dt.Hour * 60 + dt.Minute); } else { time = (int)((dt.Hour + (double)timezone) * 60 + dt.Minute); if (time > 1440) { time -= 1440; } else if (time < 0) { time += 1440; } return(time); } }
/// <summary> /// 转换为显示时间. /// </summary> /// <returns>The to local time point.</returns> /// <param name="seconds">Seconds.</param> public static string ConvertToLocalTimePoint(int seconds) { System.DateTime t = _BasicDateTime.AddSeconds((double)seconds); return(t.ToLocalTime().ToString("hh:mm:ss")); }
// Interprets a $GPRMC message public bool ParseGPRMC(string sentence) { string strParsed = "latitude: "; string Latitude = string.Empty; string Longitude = string.Empty; double Speed = -1; double Bearing = -1; // Divide the sentence into words string[] Words = GetWords(sentence); // Do we have enough values to describe our location? if (Words[3] != "" & Words[4] != "" & Words[5] != "" & Words[6] != "") { // Yes. Extract latitude and longitude // Append hours Latitude = Words[3].Substring(0, 2) + "°"; // Append minutes Latitude = Latitude + Words[3].Substring(2) + "\""; // Append hours Latitude = Latitude + Words[4]; // Append the hemisphere Longitude = Words[5].Substring(0, 3) + "°"; // Append minutes Longitude = Longitude + Words[5].Substring(3) + "\""; // Append the hemisphere Longitude = Longitude + Words[6]; // Notify the calling application of the change if (PositionReceived != null && this.bStop == false) { PositionReceived(Latitude, Longitude); } strParsed = strParsed + Latitude + " Longitude: " + Longitude; } // Do we have enough values to parse satellite-derived time? if (Words[1] != "") { // Yes. Extract hours, minutes, seconds and milliseconds int UtcHours = Convert.ToInt32(Words[1].Substring(0, 2)); int UtcMinutes = Convert.ToInt32(Words[1].Substring(2, 2)); int UtcSeconds = Convert.ToInt32(Words[1].Substring(4, 2)); int UtcMilliseconds = 0; // Extract milliseconds if it is available if (Words[1].Length > 7) { UtcMilliseconds = Convert.ToInt32(Words[1].Substring(7)); } // Now build a DateTime object with all values System.DateTime Today = System.DateTime.Now.ToUniversalTime(); System.DateTime SatelliteTime = new System.DateTime(Today.Year, Today.Month, Today.Day, UtcHours, UtcMinutes, UtcSeconds, UtcMilliseconds); // Notify of the new time, adjusted to the local time zone if (DateTimeChanged != null && this.bStop == false) { DateTimeChanged(SatelliteTime.ToLocalTime()); } strParsed = strParsed + " Time: " + SatelliteTime.ToLocalTime().ToShortTimeString(); } // Do we have enough information to extract the current speed? if (Words[7] != "") { // Yes. Parse the speed and convert it to MPH Speed = double.Parse(Words[7], NmeaCultureInfo) * MPHPerKnot; // Notify of the new speed if (SpeedReceived != null && this.bStop == false) { SpeedReceived(Speed); } // Are we over the highway speed limit? if (Speed > 55) { if (SpeedLimitReached != null && this.bStop == false) { SpeedLimitReached(); } } strParsed = strParsed + " Speed: " + Speed; } // Do we have enough information to extract bearing? if (Words[8] != "") { // Indicate that the sentence was recognized Bearing = double.Parse(Words[8], NmeaCultureInfo); if (BearingReceived != null && this.bStop == false) { BearingReceived(Bearing); } strParsed = strParsed + " Bearing: " + Bearing.ToString(); } // Does the device currently have a satellite fix? if (Words[2] != "") { switch (Words[2]) { case "A": strParsed = strParsed + " Fixed: True"; if (FixObtained != null && this.bStop == false) { FixObtained(); } break; case "V": strParsed = strParsed + " Fixed: False"; if (FixLost != null && this.bStop == false) { FixLost(); } break; } } // Indicate that the sentence was recognized if (null != GPGMCParsed && this.bStop == false) { GPGMCParsed(strParsed); } return(true); }