public static string GenerateFilterCondition(QueryDateChronologicalComparisons comparison, DateTime date) { var key = ""; var queryComparison = QueryComparisons.Equal; switch (comparison) { case QueryDateChronologicalComparisons.After: key = RowKey.CreateChronologicalKeyStart(date.AddTicks(1)); queryComparison = QueryComparisons.GreaterThan; break; case QueryDateChronologicalComparisons.AfterOrEqual: key = RowKey.CreateChronologicalKeyStart(date); queryComparison = QueryComparisons.GreaterThan; break; case QueryDateChronologicalComparisons.Before: queryComparison = QueryComparisons.LessThan; key = RowKey.CreateChronologicalKeyStart(date); break; case QueryDateChronologicalComparisons.BeforeOrEqual: queryComparison = QueryComparisons.LessThan; key = RowKey.CreateChronologicalKeyStart(date.AddTicks(1)); break; default: break; } return TableQuery.GenerateFilterCondition("RowKey", queryComparison, key); }
public static DateTime Add(DatePartType datePart, long add, DateTime dt) { switch (datePart) { case DatePartType.Year: return dt.AddYears ((int)add); case DatePartType.Quarter: return dt.AddMonths ((int)add * 3); case DatePartType.Month: return dt.AddMonths ((int)add); case DatePartType.Day: case DatePartType.DayOfYear: case DatePartType.DayOfWeek: return dt.AddDays (add); case DatePartType.Hour: return dt.AddHours (add); case DatePartType.Minute: return dt.AddMinutes (add); case DatePartType.Second: return dt.AddSeconds (add); case DatePartType.MilliSecond: return dt.AddMilliseconds (add); case DatePartType.MicroSecond: return dt.AddTicks (add * TimeSpan.TicksPerMillisecond / 1000); case DatePartType.NanoSecond: return dt.AddTicks (add * TimeSpan.TicksPerMillisecond / 1000000); default: throw new InvalidOperationException (string.Format ("Unknown DatePart type '{0}'", datePart)); } }
public DateTime? GetNextOcurrence(DateTime dateTime) { if (dateTime.TimeOfDay < FirstTime) { return dateTime.Date.AddTicks(FirstTime.Ticks); } else if (dateTime.TimeOfDay >= FirstTime && dateTime.AddTicks(1).TimeOfDay <= SecondTime) return dateTime.AddTicks(1); else return null; }
/// <summary> /// 时间戳反转为时间,有很多中翻转方法,但是,请不要使用过字符串(string)进行操作,大家都知道字符串会很慢! /// </summary> /// <param name="TimeStamp">时间戳</param> /// <param name="AccurateToMilliseconds">是否精确到毫秒</param> /// <returns>返回一个日期时间</returns> public static DateTime GetTime(long TimeStamp, bool AccurateToMilliseconds = false) { System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区 if (AccurateToMilliseconds) { return(startTime.AddTicks(TimeStamp * 10000)); } else { return(startTime.AddTicks(TimeStamp * 10000000)); } }
public static void ResetServerTime(long sTime) { System.DateTime baseDate = new System.DateTime(1970, 1, 1, 8, 0, 0); System.DateTime serverDate = baseDate.AddTicks(sTime * 10000); GetPublicTimer().ServerTimeChange(serverDate); Debug.Log("ServerTime:" + serverTime.ToString()); }
/// <summary> /// Processes the log messages. /// </summary> /// <param name="events">The events to process.</param> public void ProcessLogMessages(NLogEvents events) { var baseTimeUtc = new DateTime(events.BaseTimeUtc, DateTimeKind.Utc); var logEvents = new LogEventInfo[events.Events.Length]; // convert transport representation of log events into workable LogEventInfo[] for (int j = 0; j < events.Events.Length; ++j) { var ev = events.Events[j]; LogLevel level = LogLevel.FromOrdinal(ev.LevelOrdinal); string loggerName = events.Strings[ev.LoggerOrdinal]; var logEventInfo = new LogEventInfo(); logEventInfo.Level = level; logEventInfo.LoggerName = loggerName; logEventInfo.TimeStamp = baseTimeUtc.AddTicks(ev.TimeDelta); logEventInfo.Message = events.Strings[ev.MessageOrdinal]; logEventInfo.Properties.Add("ClientName", events.ClientName); for (int i = 0; i < events.LayoutNames.Count; ++i) { logEventInfo.Properties.Add(events.LayoutNames[i], ev.Values[i]); } logEvents[j] = logEventInfo; } this.ProcessLogMessages(logEvents); }
public void TestConvertToSysTime() { long ticksInMinute = (long)60 * 10000000; DateTime utc1601_1_1 = new DateTime(1601, 1, 1, 0, 0, 0, DateTimeKind.Utc); DateTime rawNow = DateTime.Now; DateTime now = new DateTime(rawNow.Year, rawNow.Month, rawNow.Day, rawNow.Hour, rawNow.Minute, 0, 0, rawNow.Kind); int prevSysTime = FreeBusyConverter.ConvertToSysTime(now) - 1; for (int i = 0; i < 60 * 24 * 368; i++) { DateTime future = now.AddTicks(i * ticksInMinute); int sysTime = FreeBusyConverter.ConvertToSysTime(future); DateTime check = utc1601_1_1.AddTicks(sysTime * ticksInMinute); Assert.AreEqual(future, check); Assert.AreEqual(prevSysTime + 1, sysTime); prevSysTime++; } }
private static DateTime UnixTimeValToDateTime(UInt64 tvSec, UInt64 tvUsec) { ulong ticks = (tvUsec * (TimeSpan.TicksPerMillisecond / 1000)) + (tvSec * TimeSpan.TicksPerSecond); return(epochDateTime.AddTicks((long)ticks)); }
/// <summary> /// Truncates the indicated time section to truncate. Useful when trying to remove the millisecond part of a date time. /// </summary> /// <param name="dateTime">The <see cref="DateTime"/> to truncate.</param> /// <param name="timeSectionToTruncate">A <see cref="TimeSection"/> that defines which component of the DateTime will be truncated.</param> /// <returns>A truncated <see cref="DateTime"/>.</returns> public static System.DateTime Truncate(this System.DateTime dateTime, TimeSection timeSectionToTruncate) { long ticks; switch (timeSectionToTruncate) { case TimeSection.Millisecond: ticks = TimeSpan.TicksPerSecond; break; case TimeSection.Second: ticks = TimeSpan.TicksPerMinute; break; case TimeSection.Minute: ticks = TimeSpan.TicksPerHour; break; case TimeSection.Hour: ticks = TimeSpan.TicksPerDay; break; default: throw new ArgumentOutOfRangeException("timeSectionToTruncate", "Invalid TimeSection value."); } return(dateTime.AddTicks(-(dateTime.Ticks % ticks))); }
public DateTime ToUtc() { ulong ticks = (Microseconds * (TimeSpan.TicksPerMillisecond / 1000)) + (Seconds * TimeSpan.TicksPerSecond); return(epochDateTime.AddTicks((long)ticks)); }
private static System.DateTime FromByteArrayImpl(byte[] bytes) { if (bytes.Length != TypeLengthInBytes) { throw new ArgumentOutOfRangeException(nameof(bytes), bytes.Length, $"Parsing a DateTimeLong requires exactly 12 bytes of input data, input data is {bytes.Length} bytes long."); } var year = AssertRangeInclusive(Word.FromBytes(bytes[1], bytes[0]), 1970, 2262, "year"); var month = AssertRangeInclusive(bytes[2], 1, 12, "month"); var day = AssertRangeInclusive(bytes[3], 1, 31, "day of month"); var dayOfWeek = AssertRangeInclusive(bytes[4], 1, 7, "day of week"); var hour = AssertRangeInclusive(bytes[5], 0, 23, "hour"); var minute = AssertRangeInclusive(bytes[6], 0, 59, "minute"); var second = AssertRangeInclusive(bytes[7], 0, 59, "second"); ; var nanoseconds = AssertRangeInclusive <uint>(DWord.FromBytes(bytes[11], bytes[10], bytes[9], bytes[8]), 0, 999999999, "nanoseconds"); var time = new System.DateTime(year, month, day, hour, minute, second); return(time.AddTicks(nanoseconds / 100)); }
public static void ShouldMatch(this DateTime actual, DateTime expected) { actual = actual.AddTicks(-(actual.Ticks % TimeSpan.TicksPerMillisecond)); expected = expected.AddTicks(-(expected.Ticks % TimeSpan.TicksPerMillisecond)); ShouldBeTestExtensions.ShouldBe(actual, expected); }
/// <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; }
public static DateTime RandomDate(DateTime from, DateTime to) { lock ( syncLock ) { return from.AddTicks ((long) ( random.NextDouble () * ( to.Ticks - from.Ticks ) )); } }
public static long GetJavascriptTimestamp(System.DateTime input) { return(input.AddTicks((-1) * DateTime.Parse("1970-1-1").Ticks).Ticks / 10000); //System.TimeSpan span = new System.TimeSpan(System.DateTime.Parse("1970-1-1").Ticks); //System.DateTime time = input.Subtract(span); //return (int)((int)time.Ticks / 10000); }
// ---------------------------------------------------------------------- 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(); } }
/// <summary> /// Converts a JavaScript Date object to a C# DateTime. /// </summary> /// <param name="unixTicks">JavaScript date ticks.</param> /// <returns>Converted C# DateTime.</returns> /// <see href="http://renditionprotocol.blogspot.com/2013/08/convert-javascript-epoch-milliseconds.html"/> internal static DateTime FromUnixTicks(Double unixTicks) { DateTime _01jan1970 = new DateTime(1970, 1, 1); DateTime convertedDT = _01jan1970.AddTicks(Convert.ToInt64(unixTicks) * 10000); return convertedDT; }
public static Double ToDouble(DateTime dateTime, TimeZoneKind timezoneKind) { dateTime = dateTime.AddMilliseconds(-1 * dateTime.Millisecond); var timezoneInfo = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneKindDictionary[timezoneKind]); var target = dateTime.AddTicks(-1 * timezoneInfo.BaseUtcOffset.Ticks); var timespan = new TimeSpan(target.Ticks - UnixEpoch.Ticks); return timespan.TotalMilliseconds; }
/// <summary> /// Gets specified UTC time in System.DateTime representation /// </summary> /// <param name='utcTime'>The UTC time</param> /// <returns>The UTC time stored in a System.DateTime object</returns> public static System.DateTime ToDateTime(double utcTime) { long seconds = (long)utcTime; double fraction = utcTime - seconds; return(_1_JAN_1970.AddTicks( System.TimeSpan.TicksPerSecond * seconds + (long)(System.TimeSpan.TicksPerMillisecond * 1000.0 * fraction + 0.5))); // Micro resolution }
public override string ToString() { DateTime time = new DateTime(1970, 01, 01, 0, 0, 0, 0); time = time.AddTicks((Eid * 1000) / 100); // time.ToLocalTime(); if (Format) return time.ToString("hh:mm") + " " + From + " : " + Text; return time.ToString("hh:mm") + " " + Text; }
/// <summary>Converts a string-encoded date into a Date object. </summary> public static System.DateTime StringToDate(string s) { long ticks = StringToTime(s) * TimeSpan.TicksPerMillisecond; System.DateTime date = new System.DateTime(1970, 1, 1); date = date.AddTicks(ticks); date = date.Add(TimeZone.CurrentTimeZone.GetUtcOffset(date)); return(date); }
public void PrescriptionHasEnded_False_FakeClock() { DateTime expiry = new DateTime(2012, 1, 1, 0, 0, 0); FakeClock clock = new FakeClock(expiry.AddTicks(-1)); Drug drug = new Drug("Ibuprophen"); Prescription prescription = new Prescription(expiry, clock, drug); Assert.That(prescription.HasExpired, Is.False); }
/// <summary> /// Market hours initializer given an hours since midnight measure for the market hours today /// </summary> /// <param name="referenceDate">Reference date used for as base date from the specified hour offsets</param> /// <param name="defaultStart">Time in hours since midnight to start this open period.</param> /// <param name="defaultEnd">Time in hours since midnight to end this open period.</param> public MarketHours(DateTime referenceDate, double defaultStart, double defaultEnd) { Start = referenceDate.Date.AddHours(defaultStart); End = referenceDate.Date.AddHours(defaultEnd); if (defaultEnd == 24) { // when we mark it as the end of the day other code that relies on .TimeOfDay has issues End = End.AddTicks(-1); } }
public MainForm() { InitializeComponent(); recordTime = new TimeSpan(); time = new System.DateTime(0); //streamBuffer = new MemoryStream(); //streamReader = new WaveFileReader(streamBuffer); //sampleRate = 100000; writeEvent = new EventHandler <DataAvailableEventArgs>((s, e) => { //Console.Write("Timestamp: "); //Console.Write(currTime.Ticks); //Console.Write(" "); //byte[] mybyte = Encoding.UTF8.GetBytes("hello"); //sw.Write("hello"); //Console.Write("\n"); //buffer.Read(e.Data, e.Offset, e.ByteCount); writer.Write(e.Data, e.Offset, e.ByteCount); //writer.Write(e.ByteCount); //Console.WriteLine(e.ByteCount); //sw.WriteLine("timestamp: " + time.Ticks); time = time.AddTicks(1); //resampler = new DmoResampler(capture, 10000); //resampler = new DmoResampler(streamReader, 10000); //resampler.WriteToWaveStream(sw); for (int i = 0; i < e.ByteCount; i += 8) { //Console.Write(BitConverter.ToSingle(e.Data, i) + " "); //writer.WriteSample(BitConverter.ToSingle(e.Data, i)); /*sw.WriteLine(BitConverter.ToInt32(e.Data, i) + "\t" + BitConverter.ToInt32(e.Data, i + 4));*/ /*Console.WriteLine(e.Data[i] + " " + e.Data[i + 1] + " " + e.Data[i + 2] + " " + e.Data[i + 3]);*/ } //sw.WriteLine("\n"); Console.WriteLine(e.ByteCount); }); }
public static void TestAddTicks() { DateTime dt = new DateTime(2001, 1, 1); dt = dt.AddTicks(20000000); Assert.AreEqual(dt.Year, 2001, "Bridge582 TestAddTicks Year"); Assert.AreEqual(dt.Month, 1, "Bridge582 TestAddTicks Month"); Assert.AreEqual(dt.Day, 1, "Bridge582 TestAddTicks Day"); Assert.AreEqual(dt.Hour, 0, "Bridge582 TestAddTicks Hour"); Assert.AreEqual(dt.Minute, 0, "Bridge582 TestAddTicks Minute"); Assert.AreEqual(dt.Second, 2, "Bridge582 TestAddTicks Second"); }
public void ExtendPrescription_Date_Before_Original_Expiry_Invalid() { DateTime expiry = new DateTime(2012, 1, 1, 0, 0, 0); FakeClock clock = new FakeClock(expiry.AddTicks(1)); Drug drug = new Drug("Ibuprophen"); Prescription prescription = new Prescription(expiry, clock, drug); Assert.That(prescription.HasExpired, Is.True); DateTime newExpiry = new DateTime(2011, 1, 2, 0, 0, 0); prescription.ExtendPrescription(newExpiry); }
public override object ConvertToStorageType(object value) { if (value!= null) { var dateTime = new DateTime(1753, 1, 1); if (dateTime>(DateTime) value) { var time = ((DateTime) value).TimeOfDay; return dateTime.AddTicks(time.Ticks); } dateTime = new DateTime(9999, 12, 31); if (dateTime<(DateTime) value) return dateTime; } return value; }
public static DateTime DateTimeLessThan(DateTime specified) { if (specified == System.DateTime.MinValue) { throw new ArgumentOutOfRangeException( "specified", "Cannot create DateTime less than DateTime.MinValue"); } var min = System.DateTime.MinValue; var max = specified.AddTicks(-1); return DateTime(min, max); }
/// <summary>Converts a string-encoded date into a Date object. </summary> public static System.DateTime StringToDate(System.String s) { long ticks = StringToTime(s) * TimeSpan.TicksPerMillisecond; System.DateTime date = new System.DateTime(1970, 1, 1); date = date.AddTicks(ticks); date = date.Add(TimeZone.CurrentTimeZone.GetUtcOffset(date)); return(date); /* * System.TimeSpan ts = System.TimeSpan.FromMilliseconds(System.DateField.StringToTime(s)); * return new System.DateTime(1970,1,1).Add(ts).ToLocalTime(); */ }
public static DateTime DateTimeGreaterThan(DateTime specified) { if (specified == System.DateTime.MaxValue) { throw new ArgumentOutOfRangeException( "specified", "Cannot create DateTime greater than DateTime.MaxValue"); } var min = specified.AddTicks(1); var max = System.DateTime.MaxValue; return DateTime(min, max); }
/// <summary> /// |-------------------| /// |---------------| /// |----------| /// |-----| /// </summary> /// <param name="startDate"></param> /// <param name="endOffset"></param> /// <param name="count"></param> /// <returns></returns> public static IEnumerable<DateInterval> OverlapsSameStartTimeDecreasingEndTime( DateTime startDate, TimeSpan endOffset, int count) { Debug.Assert(endOffset.Ticks > 0, "offset must be greater than zero."); Debug.Assert(count > 0, "count must be greater than zero."); var endDate = startDate.AddTicks((count - 1) * endOffset.Ticks); foreach (var number in Enumerable.Range(0, count - 1)) { var end = endDate.AddTicks(-endOffset.Ticks * number); yield return new DateInterval(startDate, end); } }
/// <summary> 获取本地时间DateTime /// </summary> /// <param name="ticks">utc时间ticks</param> /// <returns>返回DateTime</returns> public static DateTime UtcLongToLocalDateTime(long ticks) { long tempTicks = DateTime.Now.ToUniversalTime().Ticks - new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime().Ticks; if (ticks > tempTicks) { ticks = (ticks - new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime().Ticks) / 10000; } System.DateTime startTime = new System.DateTime(1970, 1, 1).ToUniversalTime(); DateTime dt = startTime.AddTicks(ticks * 10000).ToLocalTime(); return(dt); }
public void From_FromFixedDateTime_Tests(int value) { var originalPointInTime = new DateTime(1976, 12, 31, 17, 0, 0, 0, DateTimeKind.Local); DateAssert.AreEqual(value.Years().From(originalPointInTime), originalPointInTime.AddYears(value)); DateAssert.AreEqual(value.Months().From(originalPointInTime), originalPointInTime.AddMonths(value)); DateAssert.AreEqual(value.Weeks().From(originalPointInTime), originalPointInTime.AddDays(value * DaysPerWeek)); DateAssert.AreEqual(value.Days().From(originalPointInTime), originalPointInTime.AddDays(value)); DateAssert.AreEqual(value.Hours().From(originalPointInTime), originalPointInTime.AddHours(value)); DateAssert.AreEqual(value.Minutes().From(originalPointInTime), originalPointInTime.AddMinutes(value)); DateAssert.AreEqual(value.Seconds().From(originalPointInTime), originalPointInTime.AddSeconds(value)); DateAssert.AreEqual(value.Milliseconds().From(originalPointInTime), originalPointInTime.AddMilliseconds(value)); DateAssert.AreEqual(value.Ticks().From(originalPointInTime), originalPointInTime.AddTicks(value)); }
private void Update() { if (System.DateTime.Now >= NextUpdate) { NextUpdate.AddTicks(System.TimeSpan.TicksPerMillisecond * UpdateRate); Joysticks = Input.GetJoystickNames(); if (Joysticks.Length > 0) { for (int j = 0; j < Joysticks.Length; j++) { } } } }
public MusicTrack(Google.Music.Track track, string url, PrimarySource source) : base() { var epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, new System.Globalization.GregorianCalendar(), DateTimeKind.Utc); AlbumArtist = track.albumArtist; AlbumArtistSort = track.albumArtistNorm; ArtistName = track.artist; ArtistNameSort = track.artistNorm; AlbumTitle = track.album; AlbumTitleSort = track.albumNorm; Bpm = track.beatsPerMinute; CanPlay = true; CanSaveToDatabase = false; Comment = track.comment; Composer = track.composer; DateAdded = epoch.AddTicks(track.creationDate*10); DiscCount = track.totalDiscs; DiscNumber = track.disc; Duration = TimeSpan.FromMilliseconds(track.durationMillis); Genre = track.genre; LastPlayed = epoch.AddTicks(track.lastPlayed*10); MediaAttributes = TrackMediaAttributes.AudioStream | TrackMediaAttributes.Music; MimeType = "audio/mp3"; PlayCount = track.playCount; Rating = track.rating; TrackCount = track.totalTracks; TrackNumber = track.track; TrackTitle = track.title; TrackTitleSort = track.titleNorm; Year = track.year; Uri = new Hyena.SafeUri(url); ExternalId = ++id; PrimarySource = source; }
static void Main(string[] args) { //14213629935330733 //1421321881 DateTime dt = DateTime.Now; DateTime lt = new DateTime(1970, 1, 1); TimeSpan ts = dt - lt; // DateTime dtt = new DateTime(14213218810000000); dtt = dtt.AddTicks(lt.Ticks); Console.WriteLine(dtt); Console.ReadKey(); }
/// <summary> /// Converts this value to a DateTime, if it's either a timestamp value or a 64-bit integer value. /// This method is intended to be used if the value may have been returned from a projection, where timestamps /// are converted into integers in the form of a number of microseconds since the Unix epoch. /// </summary> /// <returns>The converted value.</returns> public DateTime ToDateTimeFromProjection() { switch (ValueTypeCase) { case ValueTypeOneofCase.IntegerValue: long microseconds = IntegerValue; long ticks = microseconds * TicksPerMicrosecond; return(s_unixEpochDateTime.AddTicks(ticks)); case ValueTypeOneofCase.TimestampValue: return((DateTime)this); default: throw new InvalidOperationException($"Cannot convert value of type {ValueTypeCase} to DateTime"); } }
public void UpdateNewValueAfterCacheExpires() { var cachedToggle = new CacheTestToggle(); cachedToggle.Enable(); var creationTime = new DateTime(2000, 1, 25); const int durationTicks = 1; var sut = new FixedTimeCacheDecorator(cachedToggle, TimeSpan.FromTicks(durationTicks), () => creationTime); cachedToggle.Disable(); sut.NowProvider = () => creationTime.AddTicks(durationTicks + 1); Assert.False(sut.FeatureEnabled); }
internal static object ParseEntry(PropertyEntry entry) { object obj = null; if (IsFixedLength(entry.PropertyTag.Type)) { switch (entry.PropertyTag.Type) { //ints case PropertyType.PtypInteger16: obj = BitConverter.ToInt16(entry.Value, 0); break; case PropertyType.PtypInteger32: case PropertyType.PtypErrorCode: obj = BitConverter.ToInt32(entry.Value, 0); break; case PropertyType.PtypInteger64: case PropertyType.PtypCurrency: obj = BitConverter.ToInt64(entry.Value, 0); break; //floats case PropertyType.PtypFloating32: obj = BitConverter.ToSingle(entry.Value, 0); break; case PropertyType.PtypFloating64: //case PropertyType.PtypFloatingTime: obj = BitConverter.ToDouble(entry.Value, 0); break; //other case PropertyType.PtypBoolean: obj = BitConverter.ToBoolean(entry.Value, 0); break; //PtypTime - 8 bytes; a 64-bit integer representing the number of 100-nanosecond intervals since January 1, 1601 case PropertyType.PtypTime: DateTime dt = new DateTime(1601, 1, 1, 0, 0, 0, DateTimeKind.Utc); obj = dt.AddTicks(BitConverter.ToInt64(entry.Value, 0)); break; default: return null; } } return obj; }
public static void FixCurrentTimeTo(DateTime time, bool driftSlightlyForEachCall = true) { if (time.Kind != DateTimeKind.Utc) { throw new ArgumentException(string.Format("DateTime {0} has kind {1} - it must be UTC!", time, time.Kind)); } Time.GetUtcNow = () => { var timeToReturn = time; if (driftSlightlyForEachCall) { // make time drift slightly in order to be able to verify that two separately obtained datetimes are not assumed to be equal time = time.AddTicks(1); } return timeToReturn; }; }
/** * Given a day, returns just the name to use for that day. * E.g "today", "tomorrow", "wednesday". * * @param context Context to use for resource localization * @param dateInMillis The date in milliseconds * @return */ public static String getDayName(Context context, long dateInMillis) { // If the date is today, return the localized version of "Today" instead of the actual // day name. var todayDate = DateTime.Now.ToLocalTime ().Date; long currentDay = DateTime.Today.Ticks; DateTime dateAsDay = new DateTime (); var forecastDay = dateAsDay.AddTicks (dateInMillis).ToLocalTime ().Date; if (todayDate == forecastDay) { return context.GetString (Resource.String.today); } else if (forecastDay == todayDate.AddDays (1)) { return context.GetString (Resource.String.tomorrow); } else { // Otherwise, the format is just the day of the week (e.g "Wednesday". return forecastDay.ToString ("dddd"); } }
public void ProcessLogMessages(NLogEvents events) { DateTime baseTimeUtc = new DateTime(events.BaseTimeUtc, DateTimeKind.Utc); foreach (var ev in events.Events) { LogLevel level = LogLevel.FromOrdinal(ev.LevelOrdinal); string loggerName = events.LoggerNames[ev.LoggerOrdinal]; Logger logger = LogManager.GetLogger(loggerName); var logEventInfo = new LogEventInfo(); logEventInfo.Level = level; logEventInfo.LoggerName = loggerName; logEventInfo.TimeStamp = baseTimeUtc.AddTicks(ev.TimeDelta); logEventInfo.Properties.Add("ClientName", events.ClientName); for (int i = 0; i < events.LayoutNames.Count; ++i) { logEventInfo.Properties.Add(events.LayoutNames[i], ev.Values[i]); } logger.Log(logEventInfo); } }
public Interval<DateTime> Next(DateTime from) { var dayOfWeek = from.DayOfWeek; var currentDay = new DateTime(@from.Year, @from.Month, @from.Day); if (_ruleInfo.DaysOfWeek.Contains(dayOfWeek) && IsCurrentDayOrNull(from)) { if (@from.TimeOfDay >= _ruleInfo.DayTimeFrom && @from.TimeOfDay < _ruleInfo.DayTimeTo) { return new Interval<DateTime>(@from, currentDay.AddTicks( _ruleInfo.DayTimeTo.Ticks)); } if (@from.TimeOfDay < _ruleInfo.DayTimeFrom) { return new Interval<DateTime>(currentDay.AddSeconds(_ruleInfo.DayTimeFrom.TotalSeconds), currentDay.AddSeconds(_ruleInfo.DayTimeTo.TotalSeconds)); } } var addDays = 1; var currentDayOfWeek = dayOfWeek; var currentFrom = from.AddDays(1); while (!_ruleInfo.DaysOfWeek.Contains(_dayOfWeekLoop.Next(currentDayOfWeek)) || !IsCurrentDayOrNull(currentFrom)) { if (currentFrom > MaxDateTime) { return null; } addDays++; currentDayOfWeek = _dayOfWeekLoop.Next(currentDayOfWeek); currentFrom = currentFrom.AddDays(1); } var resultDay = currentDay.AddDays(addDays); return new Interval<DateTime>(resultDay.AddSeconds(_ruleInfo.DayTimeFrom.TotalSeconds), resultDay.AddSeconds(_ruleInfo.DayTimeTo.TotalSeconds)); }
public void IsBetweenDateTimeTest() { var i = new DateTime(0); while ((i = i.AddTicks(1)) < new DateTime(40)) { var j = new DateTime(0); while ((j = j.AddTicks(1)) < new DateTime(40)) { var k = new DateTime(0); while ((k = k.AddTicks(1)) < new DateTime(60)) { var b = k.IsBetween(i, j); bool b2; if (i < j) b2 = (k >= i && k <= j); else b2 = (k >= j && k <= i); Assert.AreEqual(b, b2); } } } }
// Converts a given datetime in DMTF format to System.DateTime object. internal static System.DateTime ToDateTime(string dmtfDate) { System.DateTime initializer = System.DateTime.MinValue; int year = initializer.Year; int month = initializer.Month; int day = initializer.Day; int hour = initializer.Hour; int minute = initializer.Minute; int second = initializer.Second; long ticks = 0; string dmtf = dmtfDate; System.DateTime datetime = System.DateTime.MinValue; string tempString = string.Empty; if (String.IsNullOrEmpty(dmtf)) { return(DateTime.MinValue); } else if ((dmtf.Length != 25)) { throw new System.ArgumentOutOfRangeException(); } try { tempString = dmtf.Substring(0, 4); if (("****" != tempString)) { year = int.Parse(tempString); } tempString = dmtf.Substring(4, 2); if (("**" != tempString)) { month = int.Parse(tempString); } tempString = dmtf.Substring(6, 2); if (("**" != tempString)) { day = int.Parse(tempString); } tempString = dmtf.Substring(8, 2); if (("**" != tempString)) { hour = int.Parse(tempString); } tempString = dmtf.Substring(10, 2); if (("**" != tempString)) { minute = int.Parse(tempString); } tempString = dmtf.Substring(12, 2); if (("**" != tempString)) { second = int.Parse(tempString); } tempString = dmtf.Substring(15, 6); if (("******" != tempString)) { ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); } if (((((((((year < 0) || (month < 0)) || (day < 0)) || (hour < 0)) || (minute < 0)) || (minute < 0)) || (second < 0)) || (ticks < 0))) { throw new System.ArgumentOutOfRangeException(); } } catch (System.Exception e) { throw new System.ArgumentOutOfRangeException(null, e.Message); } if (year == 0 && month == 0 && day == 0 && hour == 0 && minute == 0 && second == 0 && ticks == 0) { return(DateTime.MinValue); } datetime = new System.DateTime(year, month, day, hour, minute, second, 0); datetime = datetime.AddTicks(ticks); System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); int UTCOffset = 0; int OffsetToBeAdjusted = 0; long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); tempString = dmtf.Substring(22, 3); if ((tempString != "******")) { tempString = dmtf.Substring(21, 4); try { UTCOffset = int.Parse(tempString); } catch (System.Exception e) { throw new System.ArgumentOutOfRangeException(null, e.Message); } OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); } return(datetime); }
public void FindEventsForwardSearchNarrowedPeriodTest() { //CommonForwardBackwardSearchEventsTest(DefineSearchRangeInside, true, false); string searchToken = string.Empty; SearchState state = SearchState.Completed; RunTest( () => { string keepAlive = string.Format("PT{0}S", _searchKeepAlive); List <EventsTopicInfo> availableEvents = GetTopics(); var recordingInfo = FindRecordingForTest(); SearchRange range = DefineSearchRangeInside(recordingInfo); DateTime start = range.Start; DateTime end = range.End; if (0 != start.Millisecond) { start = start.AddTicks(-(start.Ticks % TimeSpan.TicksPerSecond)); } if (0 != end.Millisecond) { end = end.AddTicks(-(end.Ticks % TimeSpan.TicksPerSecond)); end = end.AddSeconds(1); } List <FindEventResult> results = new List <FindEventResult>(); Dictionary <FindEventResult, XmlElement> elements1 = new Dictionary <FindEventResult, XmlElement>(); Dictionary <FindEventResult, XmlElement> elements2 = new Dictionary <FindEventResult, XmlElement>(); Dictionary <FindEventResult, XmlElement> elements = elements1; EventFilter filter = new EventFilter(); SearchScope scope = new SearchScope(); scope.IncludedRecordings = new string[] { recordingInfo.RecordingToken }; Action <DateTime, DateTime> validateAction = (startTime, endTime) => { state = SearchState.Completed; searchToken = FindEvents(scope, filter, startTime, endTime, true, null, keepAlive); results = GetAllEventsSearchResults(searchToken, null, null, "PT5S", elements, out state); Assert(results != null && results.Any(), "No events found", "Check that events list is not empty"); ValidateMessages(results); //GetMessageElements(results, rawResults, elements); ValidateRecordingEvents(recordingInfo, (trackToken) => recordingInfo.Track.Any(T => T.TrackToken == trackToken), results, elements, false, false); ValidateOrder(results, startTime, endTime); }; Action <List <FindEventResult>, Dictionary <FindEventResult, XmlElement>, DateTime, string> validateVirtualEventsAction = (events, xmlElements, time, pointType) => { var virtualEvents = events.Where(e => e.StartStateEvent && e.Time == time); var token = recordingInfo.RecordingToken; Func <FindEventResult, string, bool> checkEventTopic = (e, s) => CheckEventTopic(e, elements[e], s, TNS1NAMESPACE); var recStateEventName = "tns1:RecordingHistory/Recording/State"; Assert(virtualEvents.Any(e => token == e.RecordingToken && checkEventTopic(e, recStateEventName)), string.Format("No virtual events with topic {0} are received at {1}", recStateEventName, pointType), string.Format("Check that virtual events with topic {0} are received at {1}", recStateEventName, pointType)); var trackStateEventName = "tns1:RecordingHistory/Track/State"; var virtualTrackEvents = virtualEvents.Where(e => token == e.RecordingToken && checkEventTopic(e, trackStateEventName)); Assert(virtualTrackEvents.Any(), string.Format("No virtual events with topic {0} are received at {1}", trackStateEventName, pointType), string.Format("Check that virtual events with topic {0} are received at {1}", trackStateEventName, pointType)); Assert(recordingInfo.Track.All(t => virtualTrackEvents.Any(e => e.TrackToken == t.TrackToken)), string.Format("There is a track(s) for that event {0} is not received at {1}", trackStateEventName, pointType), string.Format("Check that for all tracks event {0} is received", trackStateEventName)); var videoParametersEventName = "tns1:RecordingHistory/Track/VideoParameters"; if (availableEvents.Any(e => e.Topic == videoParametersEventName)) { var virtualVideoEvents = virtualEvents.Where(e => token == e.RecordingToken && checkEventTopic(e, videoParametersEventName)); Assert(virtualVideoEvents.Any(), string.Format("No virtual events with topic {0} are received at {1}", videoParametersEventName, pointType), string.Format("Check that virtual events with topic {0} are received at {1}", videoParametersEventName, pointType)); Assert(recordingInfo.Track.Where(t => TrackType.Video == t.TrackType).All(t => virtualVideoEvents.Any(e => e.TrackToken == t.TrackToken)), string.Format("There is a video track(s) for that event {0} is not received at {1}", videoParametersEventName, pointType), string.Format("Check that for all video tracks event {0} is received at {1}", videoParametersEventName, pointType)); } var audioParametersEventName = "tns1:RecordingHistory/Track/AudioParameters"; if (availableEvents.Any(e => e.Topic == audioParametersEventName)) { var virtualAudioEvents = virtualEvents.Where(e => token == e.RecordingToken && checkEventTopic(e, audioParametersEventName)); Assert(virtualAudioEvents.Any(), string.Format("No virtual events with topic {0} are received at {1}", audioParametersEventName, pointType), string.Format("Check that virtual events with topic {0} are received at {1}", audioParametersEventName, pointType)); Assert(recordingInfo.Track.Where(t => TrackType.Audio == t.TrackType).All(t => virtualAudioEvents.Any(e => e.TrackToken == t.TrackToken)), string.Format("There is a audio track(s) for that event {0} is not received at {1}", audioParametersEventName, pointType), string.Format("Check that for all audio tracks event {0} is received at {1}", audioParametersEventName, pointType)); } }; validateAction(start, end); validateVirtualEventsAction(results, elements, start, "start point"); List <FindEventResult> results1 = new List <FindEventResult>(); results1.AddRange(results); elements = elements2; validateAction(end, start); validateVirtualEventsAction(results, elements, start, "start point"); validateVirtualEventsAction(results, elements, end, "end point"); List <FindEventResult> results2 = new List <FindEventResult>(); results2.AddRange(results); // compare lists CompareLists(results1, results2, elements1, elements2, "list received for StartPoint < EndPoint", "list received for StartPoint > EndPoint"); }, () => { if (state != SearchState.Completed) { ReleaseSearch(searchToken, _searchTimeout); } }); }
public System.DateTime UnixTime(uint ticks) { return(unixEpoch.AddTicks((long)ticks)); }
/// <summary> /// <para>Converts a given DMTF datetime to <see cref='System.DateTime'/> object. The returned DateTime will be in the /// current TimeZone of the system.</para> /// </summary> /// <param name='dmtfDate'>A string representing the datetime in DMTF format.</param> /// <returns> /// <para>A <see cref='System.DateTime'/> object that represents the given DMTF datetime.</para> /// </returns> /// <remarks> /// <para> Date and time in WMI is represented in DMTF datetime format. This format is explained in WMI SDK documentation. /// DMTF datetime string has an UTC offset which this datetime string represents. /// During conversion to <see cref='System.DateTime'/>, UTC offset is used to convert the date to the /// current timezone. According to DMTF format a particular field can be represented by the character /// '*'. This will be converted to the MinValue of this field that can be represented in <see cref='System.DateTime'/>. /// </para> /// </remarks> /// <example> /// <code lang='C#'> /// // Convert a DMTF datetime to System.DateTime /// DateTime date = ManagementDateTimeConverter.ToDateTime("20020408141835.999999-420"); /// </code> /// <code lang='VB'> /// ' Convert a DMTF datetime to System.DateTime /// Dim date as DateTime = ManagementDateTimeConverter.ToDateTime("20020408141835.999999-420") /// </code> /// </example> public static DateTime ToDateTime(string dmtfDate) { int year = DateTime.MinValue.Year; int month = DateTime.MinValue.Month; int day = DateTime.MinValue.Day; int hour = DateTime.MinValue.Hour; int minute = DateTime.MinValue.Minute; int second = DateTime.MinValue.Second; int millisec = 0; string dmtf = dmtfDate; DateTime datetime = DateTime.MinValue; // If the string passed is empty or null then throw // an exception if (dmtf == null) { throw new System.ArgumentOutOfRangeException(); } if (dmtf.Length == 0) { throw new System.ArgumentOutOfRangeException(); } // if the length of the string is not equal to the // standard length of the DMTF datetime then throw an exception if (dmtf.Length != SIZEOFDMTFDATETIME) { throw new System.ArgumentOutOfRangeException(); } System.Int64 ticks = 0; try { string tempString = System.String.Empty; tempString = dmtf.Substring(0, 4); if (("****" != tempString)) { year = System.Int32.Parse(tempString); } tempString = dmtf.Substring(4, 2); if (("**" != tempString)) { month = System.Int32.Parse(tempString); } tempString = dmtf.Substring(6, 2); if (("**" != tempString)) { day = System.Int32.Parse(tempString); } tempString = dmtf.Substring(8, 2); if (("**" != tempString)) { hour = System.Int32.Parse(tempString); } tempString = dmtf.Substring(10, 2); if (("**" != tempString)) { minute = System.Int32.Parse(tempString); } tempString = dmtf.Substring(12, 2); if (("**" != tempString)) { second = System.Int32.Parse(tempString); } tempString = dmtf.Substring(15, 6); if (("******" != tempString)) { ticks = (System.Int64.Parse(tempString)) * (System.TimeSpan.TicksPerMillisecond / 1000); } if (year < 0 || month < 0 || day < 0 || hour < 0 || minute < 0 || second < 0 || ticks < 0) { throw new System.ArgumentOutOfRangeException(); } } catch { throw new System.ArgumentOutOfRangeException(); } // Construct a new System.DateTime object datetime = new System.DateTime(year, month, day, hour, minute, second, millisec); // Then add the ticks calculated from the microseconds datetime = datetime.AddTicks(ticks); // Adjust the UTC time to reflect the current zone time System.TimeZone curZone = System.TimeZone.CurrentTimeZone; System.TimeSpan tickOffset = curZone.GetUtcOffset(datetime); long OffsetMins = tickOffset.Ticks / System.TimeSpan.TicksPerMinute; // Adjusting the DateTime for the current UTC int UTCOffset = 0; string tempString1 = dmtf.Substring(22, 3); long OffsetToBeAdjusted = 0; if (("***" != tempString1)) { tempString1 = dmtf.Substring(21, 4); try { UTCOffset = System.Int32.Parse(tempString1); } catch { throw new System.ArgumentOutOfRangeException(); } OffsetToBeAdjusted = UTCOffset - OffsetMins; // We have to substract the minutes from the time datetime = datetime.AddMinutes(OffsetToBeAdjusted * -1); } return(datetime); }