public ViewModel() { mgt = new ManagementClass("Win32_Processor"); procs = mgt.GetInstances(); CPU = new ObservableCollection<Model>(); timer = new DispatcherTimer(); random = new Random(); time = DateTime.Now; cpuCounter = new PerformanceCounter(); cpuCounter.CategoryName = "Processor"; cpuCounter.CounterName = "% Processor Time"; cpuCounter.InstanceName = "_Total"; ramCounter = new PerformanceCounter("Memory", "Available MBytes"); ProcessorID = GetProcessorID(); processes = Process.GetProcesses(); Processes = processes.Length; MaximumSpeed = GetMaxClockSpeed(); LogicalProcessors = GetNumberOfLogicalProcessors(); Cores = GetNumberOfCores(); L2Cache = GetL2CacheSize(); L3Cache = GetL3CacheSize(); foreach (ManagementObject item in procs) L1Cache = ((UInt32)item.Properties["L2CacheSize"].Value / 2).ToString() + " KB"; timer.Interval = TimeSpan.FromMilliseconds(1000); timer.Tick += timer_Tick; timer.Start(); for (int i = 0; i < 60; i++) { CPU.Add(new Model(time, 0,0)); time = time.AddSeconds(1); } }
public static void CreateFakeHistory(int positions) { List<ProcessHistoryDetail> fakeHistory = new List<ProcessHistoryDetail>(); Random rnd = new Random(); const int maxSec = 43200; //12h DateTime da = new DateTime(2005, 07, 08); DateTime db = da.AddSeconds(rnd.Next(maxSec)); for (int i = 0; i < positions; i++) { ProcessHistoryDetail t = new ProcessHistoryDetail(da, db); fakeHistory.Add(new ProcessHistoryDetail(t)); da = db.AddSeconds(rnd.Next(maxSec)); db = da.AddSeconds(rnd.Next(maxSec)); } XmlSerializer fakeSerializer = new XmlSerializer(typeof(List<ProcessHistoryDetail>)); using (StreamWriter write = new StreamWriter(Path.GetRandomFileName() + ".xml")) { try { fakeSerializer.Serialize(write, fakeHistory); } catch(IOException) { } } }
public void Recalculates() { var dateTime1 = new DateTime(2014, 1, 1, 1, 0, 0); var dateTime2 = new DateTime(2014, 1, 1, 1, 1, 0); var dateTime3 = new DateTime(2014, 1, 1, 2, 2, 2); var serverNameA = new ServerName("A"); var serverNameB = new ServerName("B"); var serverNameC = new ServerName("C"); System.Insert( new ServerStamp() { ServerName = serverNameA, Timestamp = dateTime1 }, new ServerStamp() { ServerName = serverNameA, Timestamp = dateTime1.AddSeconds(1) }, new ServerStamp() { ServerName = serverNameB, Timestamp = dateTime2 }, new ServerStamp() { ServerName = serverNameB, Timestamp = dateTime2.AddSeconds(1) }, new ServerStamp() { ServerName = serverNameC, Timestamp = dateTime3 }, new ServerStamp() { ServerName = serverNameC, Timestamp = dateTime3.AddSeconds(1) } ); Expect(System.TryGetServerAtStamp(dateTime1.AddSeconds(-1)), Null); Expect(System.TryGetServerAtStamp(dateTime1), EqualTo(serverNameA)); Expect(System.TryGetServerAtStamp(dateTime1.AddSeconds(1)), EqualTo(serverNameA)); Expect(System.TryGetServerAtStamp(dateTime2.AddSeconds(-1)), EqualTo(serverNameA)); Expect(System.TryGetServerAtStamp(dateTime2), EqualTo(serverNameB)); Expect(System.TryGetServerAtStamp(dateTime2.AddSeconds(1)), EqualTo(serverNameB)); Expect(System.TryGetServerAtStamp(dateTime3.AddSeconds(-1)), EqualTo(serverNameB)); Expect(System.TryGetServerAtStamp(dateTime3), EqualTo(serverNameC)); Expect(System.TryGetServerAtStamp(dateTime3.AddSeconds(1)), EqualTo(serverNameC)); }
public static LapCollection CreateLapsFromElapsedTimes(DateTime startTime, List<double> elapsedTimes, List<RouteSegment> routeSegments) { LapCollection laps = new LapCollection(); if (routeSegments.Count == 0) return laps; // justify lap times with regard to paused times during the race int currentRouteSegmentIndex = 0; for (int i = 0; i < elapsedTimes.Count; i++) { while (startTime.AddSeconds(elapsedTimes[i]) > routeSegments[currentRouteSegmentIndex].LastWaypoint.Time && currentRouteSegmentIndex < routeSegments.Count - 1) { double stoppedTime = (routeSegments[currentRouteSegmentIndex + 1].FirstWaypoint.Time.Ticks - routeSegments[currentRouteSegmentIndex].LastWaypoint.Time.Ticks) / (double)TimeSpan.TicksPerSecond; for (int j = i; j < elapsedTimes.Count; j++) { elapsedTimes[j] += stoppedTime; } currentRouteSegmentIndex++; } } // add each lap foreach (double et in elapsedTimes) { if (et > 0) laps.Add(new Lap(startTime.AddSeconds(et), LapType.Lap)); } // add start and end of each route segment as a lap foreach (RouteSegment rs in routeSegments) { laps.Add(new Lap(rs.FirstWaypoint.Time, LapType.Start)); laps.Add(new Lap(rs.LastWaypoint.Time, LapType.Stop)); } return laps; }
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.AddSeconds(Values[0]); } if (Type == CGtd.DATES_TYPE_WHEN) { int idx = time.Second; int tmp = NextValue(idx, changed); if (tmp > 0) { return time.AddSeconds(tmp); } if (tmp < 0) { changed = true; return time.AddMinutes(1).AddSeconds(Values[0] - idx); } } return time; }
public static async Task<Weather> GetWeather(string zipCode) { //Sign up for a free API key at http://openweathermap.org/appid string key = "YOUR API KEY HERE"; string queryString = "http://api.openweathermap.org/data/2.5/weather?zip=" + zipCode + ",us&appid=" + key + "&units=imperial"; var results = await DataService.getDataFromService(queryString).ConfigureAwait(false); if (results["weather"] != null) { Weather weather = new Weather(); weather.Title = (string)results["name"]; weather.Temperature = (string)results["main"]["temp"] + " F"; weather.Wind = (string)results["wind"]["speed"] + " mph"; weather.Humidity = (string)results["main"]["humidity"] + " %"; weather.Visibility = (string)results["weather"][0]["main"]; DateTime time = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); DateTime sunrise = time.AddSeconds((double)results["sys"]["sunrise"]); DateTime sunset = time.AddSeconds((double)results["sys"]["sunset"]); weather.Sunrise = sunrise.ToString() + " UTC"; weather.Sunset = sunset.ToString() + " UTC"; return weather; } else { return null; } }
static public string CreateReportFile(Contact supplier, DateTime fromDate, DateTime toDate) { DataView view = BillingDS.GetBills(fromDate, toDate, "[BillType] IN('B','G') AND [BillStatus] <> 'X' AND " + "[CancelationTime] > '" + toDate.ToString("yyyy-MM-dd HH:mm:ss") + "'"); string fileContents = GetReportFileSection(view, "1", "I"); // Active bills view = BillingDS.GetBills(DateTime.Parse("31/12/2011"), fromDate.AddSeconds(-0.5), "[BillType] = 'B' AND [BillStatus] = 'C' AND [CancelationTime] >= '" + fromDate.ToString("yyyy-MM-dd") + "' AND " + "[CancelationTime] <= '" + toDate.ToString("yyyy-MM-dd HH:mm:ss") + "'"); fileContents += GetReportFileSection(view, "0", "I"); // Canceled bills view = BillingDS.GetBills(fromDate, toDate, "[BillType] IN ('C','L') AND [BillStatus] = 'A'"); fileContents += GetReportFileSection(view, "1", "E"); // Active credit notes view = BillingDS.GetBills(DateTime.Parse("31/12/2011"), fromDate.AddSeconds(-0.5), "[BillType] IN ('C','L') AND [BillStatus] = 'C' AND [CancelationTime] >= '" + fromDate.ToString("yyyy-MM-dd") + "' AND " + "[CancelationTime] <= '" + toDate.ToString("yyyy-MM-dd HH:mm:ss") + "'"); fileContents += GetReportFileSection(view, "0", "E"); // Canceled credit notes fileContents = fileContents.TrimEnd(System.Environment.NewLine.ToCharArray()); string fileName = GetReportFileName(toDate); System.IO.File.WriteAllText(fileName, fileContents); return fileName; }
// ---------------------------------------------------------------------- public static DateTime CalcTimeMoment( DateTime baseMoment, TimeUnit offsetUnit, long offsetCount = 1, ITimeCalendar calendar = null ) { switch ( offsetUnit ) { case TimeUnit.Tick: return baseMoment.AddTicks( offsetCount ); case TimeUnit.Millisecond: DateTime offsetMillisecond = baseMoment.AddSeconds( offsetCount ); return TimeTrim.Millisecond( offsetMillisecond, offsetMillisecond.Millisecond ); case TimeUnit.Second: DateTime offsetSecond = baseMoment.AddSeconds( offsetCount ); return TimeTrim.Second( offsetSecond, offsetSecond.Second ); case TimeUnit.Minute: return new Minute(baseMoment, calendar).AddMinutes( ToInt( offsetCount ) ).Start; case TimeUnit.Hour: return new Hour( baseMoment, calendar ).AddHours( ToInt( offsetCount ) ).Start; case TimeUnit.Day: return new Day( baseMoment, calendar ).AddDays( ToInt( offsetCount ) ).Start; case TimeUnit.Week: return new Week( baseMoment, calendar ).AddWeeks( ToInt( offsetCount ) ).Start; case TimeUnit.Month: return new Month( baseMoment, calendar ).AddMonths( ToInt( offsetCount ) ).Start; case TimeUnit.Quarter: return new Quarter( baseMoment, calendar ).AddQuarters( ToInt( offsetCount ) ).Start; case TimeUnit.Halfyear: return new Halfyear( baseMoment, calendar ).AddHalfyears( ToInt( offsetCount ) ).Start; case TimeUnit.Year: return new Year( baseMoment, calendar ).AddYears( ToInt( offsetCount ) ).Start; default: throw new InvalidOperationException(); } }
public void FiresSkippedEventsInSameCallToScan() { int count = 0; var time = new DateTime(2015, 08, 11, 10, 30, 0); var sevent = new ScheduledEvent("test", new[] { time.AddSeconds(-2), time.AddSeconds(-1), time}, (n, t) => count++); sevent.Scan(time); Assert.AreEqual(3, count); }
/// <summary> /// Creates an instance of WorkTimeRangeVm for the given <see cref="Soheil.Model.WorkBreak"/> /// </summary> /// <param name="wbreak"></param> protected WorkTimeRangeVm(WorkBreak wbreak, DateTime offset) { Start = offset.AddSeconds(wbreak.StartSeconds); End = offset.AddSeconds(wbreak.EndSeconds); Color = DefaultColors.WorkBreak; Id = wbreak.Id; IsShift = false; }
/// <summary> /// Creates an instance of WorkTimeRangeVm for the given <see cref="Soheil.Model.WorkShift"/> /// </summary> /// <param name="shift"></param> public PPItemWorkTime(WorkShift shift, DateTime dayStart) { DayStart = dayStart; Start = dayStart.AddSeconds(shift.StartSeconds); End = dayStart.AddSeconds(shift.EndSeconds); Id = shift.Id; Model = shift; }
public void TestMethod6() { DateTime Date = new DateTime(); Methods c = new Methods(); string d = "Mon"; string a = "Thu"; Assert.AreEqual(d,c.TradeStop(Date.AddSeconds(1463674549))); Assert.IsFalse(a==c.TradeStop(Date.AddSeconds(1463674549))); }
public void SkipsEventsUntilTime() { int count = 0; var time = new DateTime(2015, 08, 11, 10, 30, 0); var sevent = new ScheduledEvent("test", new[] { time.AddSeconds(-2), time.AddSeconds(-1), time }, (n, t) => count++); // skips all preceding events, not including the specified time sevent.SkipEventsUntil(time); Assert.AreEqual(time, sevent.NextEventUtcTime); }
/// <summary> /// Creates an instance of WorkTimeRangeVm for the given <see cref="Soheil.Model.WorkShift"/> /// </summary> /// <param name="shift"></param> protected WorkTimeRangeVm(WorkShift shift, DateTime offset) { Start = offset.AddSeconds(shift.StartSeconds); End = offset.AddSeconds(shift.EndSeconds); Color = shift.WorkShiftPrototype.Color; Id = shift.Id; Children = new List<WorkTimeRangeVm>(); IsShift = true; }
public static DateTime UnixTimeStampToDateTime(double unixTimeStamp, bool localTime) { // Unix timestamp is seconds past epoch DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); if (localTime) dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime(); else dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToUniversalTime(); return dtDateTime; }
public void IncrementedTimeTest() { DateTime initial = new DateTime(2007, 10, 02, 14, 32, 10); Thread.Sleep(100); Assert.AreEqual(global::System.Current.DateTime.Now, initial); Assert.AreEqual(global::System.Current.DateTime.Now, initial.AddSeconds(1 * 310)); Thread.Sleep(100); Assert.AreEqual(global::System.Current.DateTime.Now, initial.AddSeconds(2 * 310)); Assert.AreEqual(global::System.Current.DateTime.Now, initial.AddSeconds(3 * 310)); }
public void SynchronizesData() { var time = new DateTime(2016, 03, 03, 12, 05, 00); var stream1 = Enumerable.Range(0, 10).Select(x => new Tick {Time = time.AddSeconds(1)}).GetEnumerator(); var stream2 = Enumerable.Range(0, 5).Select(x => new Tick {Time = time.AddSeconds(2)}).GetEnumerator(); var stream3 = Enumerable.Range(0, 20).Select(x => new Tick {Time = time.AddSeconds(0.5)}).GetEnumerator(); var previous = DateTime.MinValue; var synchronizer = new SynchronizingEnumerator(stream1, stream2, stream3); while (synchronizer.MoveNext()) { Assert.That(synchronizer.Current.EndTime, Is.GreaterThanOrEqualTo(previous)); previous = synchronizer.Current.EndTime; } }
private void Time_Changed(object sender, DateTimeValueChangedEventArgs e) { System.DateTime? valueOpt = e.NewDateTime; if (valueOpt.HasValue && TimePicker != null) { var value = valueOpt.Value; int seconds = value.Second + value.Minute * 60 + value.Hour * 3600; double roundToInterval = 60 * 30; seconds = (int) (Math.Round(seconds / roundToInterval) * roundToInterval); var newValue = new System.DateTime(); newValue = newValue.AddSeconds(-getSecondsFromStartOfDay(newValue)); newValue = newValue.AddSeconds(seconds); TimePicker.Value = newValue; } }
// redefine the timeAxis, given another DfsfileInfo, new interval and spacing public int TimeAxis_Project(DfsUtilities fi_project, ref int timeStep_start, ref int timeStep_end, int timeStep_freq) { //edit timeaxis CheckTimeStartandEnd(ref timeStep_start, ref timeStep_end); if (timeStep_start > 0) { System.DateTime sdt = DfsDateTime2DateTime(fi_project.tAxis_StartDateStr, fi_project.tAxis_StartTimeStr); if (fi_project.tAxis_EUMUnit != (int)DHI.Generic.MikeZero.eumUnit.eumUsec) { return(_err("JdfsFileInfo only supports files with timeaxis in eumUsec")); } sdt = sdt.AddSeconds(tAxis_dTStep * timeStep_start); tAxis_StartDateStr = MakeDfsDate(sdt); tAxis_StartTimeStr = MakeDfsTime(sdt); } if (timeStep_freq != 1) { if (timeStep_freq < 1) { return(_err("JdfsFileInfo timeStepFreq must be integer>=1")); } tAxis_dTStep = fi_project.tAxis_dTStep * timeStep_freq; } return(0); }
public static DateTime ToDateTimeValue(this double timeValue) { System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); startTime = startTime.AddSeconds(timeValue); //startTime = startTime.AddHours(8);//转化为北京时间(北京时间=UTC时间+8小时 ) return(startTime); }
public static System.DateTime ToDateUnixTime(this long utc) { //return new DateTime(1970, 1, 1, 0, 0, 0).AddMinutes((DateTime.Now - DateTime.UtcNow).TotalMinutes).AddMilliseconds(utc); var epoch = new System.DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); return(epoch.AddSeconds(utc)); }
public static DateTime GenericTimeStamp(long time) { System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区 DateTime dt = startTime.AddSeconds(time); return(dt); }
private void timer1_Tick(object sender, EventArgs e) { TimeP = TimeP.AddSeconds(+1); label1.Text = TimeP.ToString("HH"); label2.Text = TimeP.ToString("mm"); label3.Text = TimeP.ToString("ss"); }
public static async Task <List <Game> > LoadGamesBasedOnFilters(string genre, string platform, int MinRating = 1, int MaxRating = 100) { string url = "games/"; var query = queryProcess(MinRating, MaxRating, genre: genre, platform: platform); using (HttpResponseMessage response = await ApiHelper.ApiClient.PostAsync(url, new StringContent(query))) { string res = response.ReasonPhrase; if (response.IsSuccessStatusCode || res == "Server Error") { var games = await response.Content.ReadAsAsync <List <Game> >(); System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); foreach (var game in games) { game.release_date = dateTime.AddSeconds(game.first_release_date); } return(games); } else { var emptyGameList = new List <Game>(); return(emptyGameList); // throw new Exception(response.ReasonPhrase); } } }
public static async Task <List <Game> > LoadGamesBasedOnSearch(string name) { string url = "games/"; var query = $@" fields genres.name,genres.slug,cover.url,cover.image_id,name,rating,first_release_date,platforms.name; where popularity>1&rating>1; search ""{name}""; limit 20;"; using (HttpResponseMessage response = await ApiHelper.ApiClient.PostAsync(url, new StringContent(query))) { if (response.IsSuccessStatusCode) { var games = await response.Content.ReadAsAsync <List <Game> >(); System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); foreach (var game in games) { dateTime = dateTime.AddSeconds(game.first_release_date); game.release_date = dateTime; } return(games); } else { throw new Exception(response.ReasonPhrase); } } }
/// <summary> /// 将Unix时间戳转换为DateTime类型时间 /// </summary> /// <param name="d"></param> /// <returns></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); return(time); }
public static DateTime ToDateTime(long unixTimeStamp) { // Unix timestamp is seconds past epoch var result = unixBaseDate.AddSeconds(unixTimeStamp).ToLocalTime(); return(result); }
public DateTime UnixTimeToDateTime(string text) { System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); // Add the number of seconds in UNIX timestamp to be converted. dateTime = dateTime.AddSeconds(Convert.ToDouble(text)); return(dateTime); }
public static async Task <Game> ShowOneGame(int gameId) { string url = "games/"; var query = $@" fields genres.name,cover.image_id,name, rating,first_release_date,platforms.name, storyline,summary,popularity,screenshots.image_id,videos.video_id,videos.name, expansions.name,expansions.cover.image_id,involved_companies.company.name; where id={gameId};"; using (HttpResponseMessage response = await ApiHelper.ApiClient.PostAsync(url, new StringContent(query))) { if (response.IsSuccessStatusCode) { var games = await response.Content.ReadAsAsync <List <Game> >(); System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); foreach (var game in games) { dateTime = dateTime.AddSeconds(game.first_release_date); game.release_date = dateTime; if (game.cover != null) { game.cover.gameId = gameId; } if (game.screenshots != null) { foreach (var screenshot in game.screenshots) { screenshot.gameId = gameId; } } if (game.videos != null) { foreach (var videos in game.videos) { videos.gameId = gameId; } } if (game.expansions != null) { foreach (var expansion in game.expansions) { expansion.gameId = gameId; } } } return(games[0]); } else { throw new Exception(response.ReasonPhrase); } } }
//秒时间戳转成时间 public static System.DateTime StampToTimes(this int stamp) { System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区 DateTime dt = startTime.AddSeconds(stamp); return(dt); }
/// <summary> /// 时间戳转为C#格式时间 /// </summary> /// <param name=”timeStamp”></param> /// <returns></returns> public static DateTime ToUtcDateTime(this long unixTimeStamp) { System.DateTime startTime = new System.DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); DateTime dt = startTime.AddSeconds(unixTimeStamp); return(dt); }
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); }
//남은 시간은 전달해서 남은시간 카운트? IEnumerator ManageMentRecovery(bool isRecovery, string startTime, float managementRecoverTime) { while (isRecovery) { yield return(null); System.DateTime nowTime = System.Convert.ToDateTime(System.DateTime.Now); System.DateTime firstManagementTime = System.Convert.ToDateTime(DateTime.Parse(startTime)); System.TimeSpan completeTime = firstManagementTime.AddSeconds(managementRecoverTime) - nowTime; string tempSecond; if (completeTime.Seconds < 10) { tempSecond = "0" + completeTime.Seconds; } else { tempSecond = completeTime.Seconds.ToString(); } txtManageRecoveryTime.text = completeTime.Minutes.ToString() + ":" + tempSecond; if (completeTime.Minutes <= 0 && completeTime.Seconds <= 0) { Debug.Log("매니지 먼트 회복"); isRecovery = false; StopAllCoroutines(); Message.Send <AloneGameManageMentRecoveryMsg>(new AloneGameManageMentRecoveryMsg()); } } }
public static DateTime parstUnixTime(long time) { System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区 DateTime dt = startTime.AddSeconds(time / 1000); return(dt); }
/// <summary> /// Get current IP Camera's time zone and time. /// </summary> /// <returns></returns> void GetTime(out DateTime timeUtc, out TimeZoneInfo timeZone, out string ntpServer, out bool useNtp) { ///GetTime.cgi[?JsVar=variable[&OnJs=function]] timeUtc = DateTime.MinValue; timeZone = TimeZoneInfo.Local; ntpServer = ""; useNtp = false; RovioResponse dic = this.Request("/GetTime.cgi"); if (dic == null) return; long sec1970; if (!(dic.ContainsKey("Sec1970") && long.TryParse(dic["Sec1970"], out sec1970))) return; int timeZoneMinutes; if (!(dic.ContainsKey("TimeZone") && int.TryParse(dic["TimeZone"], out timeZoneMinutes))) return; DateTime date1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); timeUtc = date1970.AddSeconds(sec1970); timeZone = CreateTimeZone(TimeSpan.FromMinutes(-timeZoneMinutes)); ntpServer = dic.ContainsKey("NtpServer") ? dic["NtpServer"] : ""; useNtp = dic.ContainsKey("UseNtp") ? (dic["UseNtp"] == "1") : false; }
public static DateTime CalculateSessionDataRowDate(DateTime startDate, int interval, int row) { var seconds = interval * row ; var calculatedDate = startDate.AddSeconds(seconds); return calculatedDate; }
public static DateTime NSDateToDateTime(NSDate date) { DateTime reference = new DateTime(2001, 1, 1, 0, 0, 0); DateTime currentDate = reference.AddSeconds(date.SecondsSinceReferenceDate); DateTime localDate = currentDate.ToLocalTime (); return localDate; }
// Vibrates the controller with a given force, specific vibration motor and for a selected amount of time public static void controllerVibration(string motor, float force, double vibrateTime) { /* while (timer <= timerend) { if (motor == "Rough") GamePad.SetVibration(playerIndex, force, 0); if (motor == "Smooth") GamePad.SetVibration(playerIndex, 0, force); if (motor == "Both") GamePad.SetVibration(playerIndex, force, force); timert += Time.deltaTime; } if (timer > timerend) { GamePad.SetVibration(playerIndex, 0, 0); timer = 0; }*/ timer = DateTime.Now; timerend = timer.AddSeconds(vibrateTime); while (timer.Second < timerend.Second) { if (motor == "Rough") GamePad.SetVibration(playerIndex, force, 0); if (motor == "Smooth") GamePad.SetVibration(playerIndex, 0, force); if (motor == "Both") GamePad.SetVibration(playerIndex, force, force); timer = DateTime.Now; } GamePad.SetVibration(playerIndex, 0, 0); //timer = timerend = 0; }
public static DateTime UnixTimeStampToDateTime(this string unixTimeStamp) { // Unix timestamp is seconds past epoch var dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); dtDateTime = dtDateTime.AddSeconds(unixTimeStamp.ToDouble()).ToLocalTime(); return dtDateTime; }
public static DateTime JavaTimeStampToDateTime(double javaTimeStamp) { // Java timestamp is millisecods past epoch var dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0); dtDateTime = dtDateTime.AddSeconds(Math.Round(javaTimeStamp / 1000)).ToLocalTime(); return dtDateTime; }
/// <summary> /// Convert a unix timestamp to a .net datetime /// </summary> /// <param name="unixTimeStamp"></param> /// <returns></returns> public static DateTime FromUnixTimeStamp(double unixTimeStamp) { // Unix timestamp is seconds past epoch var dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0); dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime(); return dtDateTime; }
public 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]; Stream s = null; try { s = new FileStream(filePath, FileMode.Open, 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); dt = dt.AddSeconds(secondsSince1970); dt = dt.AddHours(TimeZone.CurrentTimeZone.GetUtcOffset(dt).Hours); return dt; }
protected override DateTime? GetBuildTime() { if (!Configuration.UseBuildTime) return null; const int peHeaderOffset = 60; const int linkerTimestampOffset = 8; FileStream s = null; var b = new byte[2048]; try { var filePath = GetFirstAssembly().Location; s = new FileStream(filePath, FileMode.Open, FileAccess.Read); s.Read(b, 0, 2048); } finally { s?.Close(); } var i = BitConverter.ToInt32(b, peHeaderOffset); var secondsSince1970 = BitConverter.ToInt32(b, i + linkerTimestampOffset); var dt = new DateTime(1970, 1, 1, 0, 0, 0); dt = dt.AddSeconds(secondsSince1970); dt = dt.AddHours(TimeZone.CurrentTimeZone.GetUtcOffset(dt).Hours); return dt; }
public static DateTime FromUnixTime(this long seconds) { var time = new DateTime(1970, 1, 1); time = time.AddSeconds(seconds); return time.ToLocalTime(); }
public static DateTime UnixTimeStampToDateTime(double unixTimeStamp) { // Unix timestamp is seconds past epoch System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc); dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime(); return dtDateTime; }
//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; }
public string TempActivityDataToEcs() { try { string sql = string.Format(@"SELECT Id,prize_name,name,job1,job2,mobile,hotel,province,province_id,city, city_id,area,area_id,address,createtime,openid,nickname FROM dbo.TempActivityData WHERE handle_status IS NULL OR handle_status <>'succ' ORDER BY Id"); DataTable dt = SqlHelper.ExecuteDataTable(sql); int id = 0; System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区 foreach (DataRow dr in dt.Rows) { id = Convert.ToInt32(dr["Id"]); ActivityData data = new ActivityData(); data.PrizeName = dr["prize_name"].ToString(); data.Name = dr["name"].ToString(); data.PositionType = dr["job1"].ToString(); data.Position = dr["job2"].ToString(); data.Phone = dr["mobile"].ToString(); data.HotelOrMdName = dr["hotel"].ToString(); data.ProvinceName = dr["province"].ToString(); data.ProvinceId = Convert.ToInt32(dr["province_id"]); data.CityName = dr["city"].ToString(); data.CityId = Convert.ToInt32(dr["city_id"]); data.AreaName = dr["area"].ToString(); data.AreaId = Convert.ToInt32(dr["area_id"]); data.Address = dr["address"].ToString(); data.AddDate = startTime.AddSeconds(Convert.ToDouble(dr["createtime"])).ToString("yyyy-MM-dd HH:mm:ss"); //时间戳转日期 data.OpenId = dr["openid"].ToString(); data.NickName = dr["nickname"].ToString(); string result = HandleAction(data); if (result == "succ") { //更新状态为succ sql = string.Format(@"UPDATE dbo.TempActivityData SET handle_status = 'succ',handle_date= getdate(),handle_result_message = 'succ' WHERE Id ={0} ", id); SqlHelper.ExecuteNonQuery(CommandType.Text, sql); } else { //更新状态为fail sql = string.Format(@"UPDATE dbo.TempActivityData SET handle_status = 'fail',handle_date= getdate(),handle_result_message = '{0}' WHERE Id ={1} ", result, id); SqlHelper.ExecuteNonQuery(CommandType.Text, sql); } } return("处理完毕"); } catch (Exception ex) { Common.LogHelper.WriteLog(ex.ToString()); return("fail"); } }
public string unixConvert(double x) { System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); dateTime = dateTime.AddSeconds(x); string printDate = dateTime.ToString("dd/M/yyyy", null) + " " + dateTime.ToShortTimeString(); return(printDate); }
DateTime getDate(double millisecound) { DateTime day = new System.DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc).ToLocalTime(); day = day.AddSeconds(millisecound).ToLocalTime(); return(day); }
/// <summary> /// 将Unix时间戳转换为DateTime类型时间;(本地时区时间) /// </summary> /// <param name=”d”>double 型数字</param> /// <returns>DateTime</returns> public static System.DateTime ConvertLongDateTime(long d) { System.DateTime time = System.DateTime.MinValue; System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); //TODO: time = startTime.AddSeconds(d - 8 * 60 * 60); return(time); }
private string conv(string timestamp) { long time = long.Parse(timestamp); System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); dateTime = dateTime.AddSeconds(time); return(dateTime.Day.ToString() + "/" + dateTime.Month.ToString() + "/" + dateTime.Year.ToString()); }
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 Quote(string quote) { Name = quote.Substring(2, 5); Value = quote.Substring(10).Split(',')[0]; DateTime date = new System.DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); Date = date.AddSeconds(Convert.ToDouble(quote.Split(':')[2].Split('}')[0])); }
DateTime gettimefromepochtime(double timestamp) { // First make a System.DateTime equivalent to the UNIX Epoch. System.DateTime dateTime = new System.DateTime(1980, 1, 1, 0, 0, 0, 0); // Add the number of seconds in UNIX timestamp to be converted. return(dateTime = dateTime.AddSeconds(timestamp).ToLocalTime()); }
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}"); }
public static DateTime GetDate(int unixTime) { DateTime date = new System.DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc).ToLocalTime(); date = date.AddSeconds(unixTime).ToLocalTime(); return(date); }
public DateTime TimestamToDate(int ValueTime) { DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); dateTime = dateTime.AddSeconds(ValueTime).AddHours(-3); return(dateTime); }
public static DateTime GetDateTimeFromTimestamp(string timestamp) { // First make a System.DateTime equivalent to the UNIX Epoch. System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); // Add the number of seconds in UNIX timestamp to be converted. return(dateTime.AddSeconds(Double.Parse(timestamp))); }
/// <summary> /// 将Unix时间戳转换为DateTime类型时间 /// </summary> /// <param name="d"></param> /// <returns></returns> public static DateTime ConvertIntDateTime(double d) { DateTime time = System.DateTime.MinValue; DateTime startTime = new System.DateTime(1970, 1, 1); time = startTime.AddSeconds(d); return(time); }
// default constructor used to build a new OAuth 2.0 token public OAuth2Token() { // build a new date/time object representing now System.DateTime now = System.DateTime.UtcNow; // set the expires on to now + expires_in this._expires_on = now.AddSeconds(this._expires_in); }