private static HistoryEvent ToHistoryEvent(SqlDataReader reader, DateTimeOffset?executionStartTime) { var evt = new HistoryEvent { Timestamp = ((DateTime)reader["Timestamp"]).ToUniversalTime(), EventType = reader["EventType"].ToString(), EventId = reader["EventId"] is DBNull ? null : (int?)reader["EventId"], Name = reader["Name"].ToString(), Result = reader["Result"].ToString(), Details = reader["Details"].ToString(), SubOrchestrationId = reader["SubOrchestrationId"].ToString(), }; var rawScheduledTime = reader["ScheduledTime"]; if (!(rawScheduledTime is DBNull)) { evt.ScheduledTime = ((DateTime)rawScheduledTime).ToUniversalTime(); } else if (evt.EventType == "ExecutionCompleted") { evt.ScheduledTime = executionStartTime?.ToUniversalTime(); } if (evt.ScheduledTime.HasValue) { evt.DurationInMs = (evt.Timestamp - evt.ScheduledTime.Value).TotalMilliseconds; } return(evt); }
public void DateTimeOffset_Can_Specifity_Your_Local_Time_From_Utc_Point_Of_View() { var jonsTime = new DateTimeOffset(2011, 4, 1, 21, 24, 0, TimeSpan.FromHours(1)); var localTime = new DateTime(2011, 4, 1, 20, 24, 0); Assert.That(jonsTime.ToUniversalTime().Hour, Is.EqualTo(localTime.Hour)); }
internal static string ToAtomString(DateTimeOffset dateTime) { if (dateTime.Offset == zeroOffset) { return dateTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture); } return dateTime.ToString("yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture); }
public static string ToApiDateTimeFormat(this DateTimeOffset?date) { if (date != null) { return(date?.ToUniversalTime().ToString(ApiDateFormat)); } return(string.Empty); }
private string AsString(DateTimeOffset dateTime) { if (dateTime.Offset == zeroOffset) { return dateTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture); } return dateTime.ToString("yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture); }
public void WriteDate(DateTimeOffset datetime) { this.writeAmf3Type(Amf3Type.Date); UInt29 remainIndex = 0; remainIndex.WriteAsRefTo(false,this.writer_); var utcTime = datetime.ToUniversalTime(); var totalMilliseconds = utcTime.ToUnixTime(); this.writer_.WriteDouble(totalMilliseconds); }
private string AsString(DateTimeOffset dateTime) { if (dateTime.Offset == Atom10FeedFormatter.zeroOffset) { return dateTime.ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss Z", CultureInfo.InvariantCulture); } StringBuilder builder = new StringBuilder(dateTime.ToString("ddd, dd MMM yyyy HH:mm:ss zzz", CultureInfo.InvariantCulture)); builder.Remove(builder.Length - 3, 1); return builder.ToString(); }
public UserList(string usersFile, DateTimeOffset startOfWeek) : this(usersFile) { StartOfPeriod = startOfWeek.ToUniversalTime(); EndOfPeriod = StartOfPeriod.AddDays(7); // We only count events attached to posts (questions or answers) that we created at most 3 days before // the week starts. The idea is to not keep rewarding users for old entries that are getting upticks FirstStackOverflowPost = QueryHelpers.GetIdOfFirstPostOfDay(StartOfPeriod.AddDays(-3)); }
public static XElement TIME(string name, DateTimeOffset time) { var t1 = time.ToUniversalTime(); var t2 = time.ToLocalTime().ToString("G"); return new XElement( XN.time, PROP(name), new XAttribute(XN.datetime, t1), t2); }
public void ConvertDateTimeValue_NonStandardPrimitives_CustomTimeZoneInfo(DateTimeOffset valueToConvert) { // Arrange & Act TimeZoneInfoHelper.TimeZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); object actual = EdmPrimitiveHelpers.ConvertPrimitiveValue(valueToConvert, typeof(DateTime)); // Assert DateTime dt = Assert.IsType<DateTime>(actual); Assert.Equal(valueToConvert.ToUniversalTime().ToOffset(new TimeSpan(-8, 0, 0)).DateTime, dt); }
public void ConvertDateTimeValue_NonStandardPrimitives_DefaultTimeZoneInfo(DateTimeOffset valueToConvert) { // Arrange & Act TimeZoneInfoHelper.TimeZone = null; object actual = EdmPrimitiveHelpers.ConvertPrimitiveValue(valueToConvert, typeof(DateTime)); // Assert DateTime dt = Assert.IsType<DateTime>(actual); Assert.Equal(valueToConvert.ToUniversalTime().ToOffset(TimeZoneInfo.Local.BaseUtcOffset).DateTime, dt); }
public void DateTimeOffSet() { //System.DateTimeOffset (.NET 2.0SP1 / .NET 3.5) DateTimeOffset myTime = new DateTimeOffset(2015, 11, 12, 9, 13, 0, TimeSpan.FromHours(1)); Console.WriteLine( myTime); Console.WriteLine(myTime.ToUniversalTime()); //System.TimeZoneInfo (.NET 3.5) }
public void DateTimeOffset() { // System.DateTimeOffset (.NET 3.5) DateTimeOffset axelsTime = new DateTimeOffset(2011, 4, 1, 21, 24, 0, TimeSpan.FromHours(1)); //Console.WriteLine(axelsTime); //Console.WriteLine(axelsTime.ToUniversalTime()); DateTimeOffset robsTime = new DateTimeOffset(2011, 4, 1, 10, 24, 0, TimeSpan.FromHours(-10)); Assert.AreEqual(axelsTime, robsTime); Assert.AreEqual(axelsTime.ToUniversalTime(), robsTime.ToUniversalTime()); }
public WaitHandle AbsoluteTimer(DateTimeOffset expireAt) { var handle = CreateWaitableTimer(IntPtr.Zero, true, null); var dueTime = expireAt.ToUniversalTime().ToFileTime(); SetWaitableTimer(handle, ref dueTime, 0, IntPtr.Zero, IntPtr.Zero, false); var safeHandle = new SafeWaitHandle(handle, true); return new TimerWaitHandle(safeHandle); }
public void CopyFromDocument() { var mapper = CreateMapper(); var doc = new Document(); var ts = new DateTimeOffset(new DateTime(2013, 1, 1)); doc.Add(new Field("TimeStampOffset", ts.ToUniversalTime().Ticks.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED)); mapper.CopyFromDocument(doc, 0, this); Assert.That(TimeStampOffset, Is.EqualTo(ts)); }
public modified() { point_in_time = new DateTimeOffset(2011,09,24,22,00,0,0, 2.Hours()); // last-modified: 24 Sep 2011 23:11:00 +0200 (21:00:00 GMT) given_resource( "/resource", resource=>resource.Map<ResourceWithLastModified>().LastModified(_=> _.LastModified), new ResourceWithLastModified { LastModified = point_in_time + 1.Hours() }); // if-modified-since: 24 Sep 2011 22:00:00 +0200 (20:00:00 GMT) given_request_header("if-modified-since", point_in_time.ToUniversalTime().ToString("R")); when_executing_request("/resource"); }
private string DateTimeSerializeToJSON(DateTime dateTime) { var value = new DateTimeOffset(dateTime); var kind = dateTime.Kind; var num = ((value.ToUniversalTime().Ticks - new DateTime(0x7b2, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks) / 0x2710L); var str = string.Empty; switch (kind) { case DateTimeKind.Unspecified: case DateTimeKind.Local: TimeSpan offset = value.Offset; str = offset.Hours.ToString("+00;-00", CultureInfo.InvariantCulture) + offset.Minutes.ToString("00;00", CultureInfo.InvariantCulture); break; } return ("\"\\/Date(" + num.ToString(CultureInfo.InvariantCulture) + str + ")\\/\""); }
public async Task Defer(DateTimeOffset approximateDueTime, Dictionary<string, string> headers, byte[] body) { using (var connection = await _connectionHelper.GetConnection()) { using (var command = connection.CreateCommand()) { command.CommandText = string.Format(@" INSERT INTO ""{0}"" (""due_time"", ""headers"", ""body"") VALUES (@due_time, @headers, @body)", _tableName); command.Parameters.Add("due_time", NpgsqlDbType.Timestamp).Value = approximateDueTime.ToUniversalTime().DateTime; command.Parameters.Add("headers", NpgsqlDbType.Text).Value = _headerSerializer.SerializeToString(headers); command.Parameters.Add("body", NpgsqlDbType.Bytea).Value = body; await command.ExecuteNonQueryAsync(); } connection.Complete(); } }
public async Task <IEnumerable <Event> > GetUserTeamEventsAsync( string userToken, DateTimeOffset?startDateTime = null, DateTimeOffset?endDateTime = null, int?teamId = null, bool?dashboardTeamsOnly = null) { var properties = new Dictionary <string, string> { { nameof(userToken), userToken }, { nameof(startDateTime), startDateTime?.ToUniversalTime().ToString(DATETIME_FORMAT) }, { nameof(endDateTime), endDateTime?.ToUniversalTime().ToString(DATETIME_FORMAT) }, { nameof(teamId), teamId?.ToString() }, { nameof(dashboardTeamsOnly), dashboardTeamsOnly?.ToString() }, }; var response = await SendRequestAsync <IEnumerable <Event> >( "User_GetTeamEvents", properties); return(response.Data); }
public static async Task <DateTimeOffset> CursorEvents(this IDataService service, string collection, DateTimeOffset from, Func <Event, Task> action, int batchSize = 1000) { IEnumerable <Event> events = null; string skipToken = null; DateTimeOffset?end = null; DateTimeOffset start = DateTimeOffset.UtcNow; do { skipToken = events?.LastOrDefault()?.Id; events = await service.GetEventsAsync(collection, from, skipToken, batchSize); foreach (var ev in events) { await action(ev); } end = events.LastOrDefault()?.TrackAt; } while(events.Count() == batchSize); return(new DateTimeOffset(Math.Max(start.Ticks, end?.ToUniversalTime().Ticks ?? 0), TimeSpan.Zero)); }
private static string ExpectedDateTimeOffsetSerialization(DateTimeOffset dto) { DateTime utc = dto.ToUniversalTime().UtcDateTime; return "\"" + utc.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK", CultureInfo.InvariantCulture) + "\""; }
/// <summary> /// Convert specified <see cref="DateTimeOffset"/> to <see cref="Int64"/> as MessagePack defacto-standard. /// </summary> /// <param name="value"><see cref="DateTimeOffset"/>.</param> /// <returns> /// UTC epoc time from 1970/1/1 0:00:00, in milliseconds. /// </returns> public static long FromDateTimeOffset( DateTimeOffset value ) { // Note: microseconds and nanoseconds should always truncated, so deviding by integral is suitable. return value.ToUniversalTime().Subtract( _unixEpocUtc ).Ticks / _ticksToMilliseconds; }
public static string DateToString(DateTimeOffset dateTime) { // Format according to RFC1123; 'r' uses invariant info (DateTimeFormatInfo.InvariantInfo) return dateTime.ToUniversalTime().ToString("r", CultureInfo.InvariantCulture); }
public static string DateToString(DateTimeOffset dateTime) { return dateTime.ToUniversalTime().ToString("r", (IFormatProvider)CultureInfo.InvariantCulture); }
internal static object ConvertUnsupportedPrimitives(object value) { if (value != null) { Type type = value.GetType(); // Note that type cannot be a nullable type as value is not null and it is boxed. switch (Type.GetTypeCode(type)) { case TypeCode.Char: return new String((char)value, 1); case TypeCode.UInt16: return (int)(ushort)value; case TypeCode.UInt32: return (long)(uint)value; case TypeCode.UInt64: return checked((long)(ulong)value); case TypeCode.DateTime: DateTime dateTime = (DateTime)value; TimeZoneInfo timeZone = TimeZoneInfoHelper.TimeZone; if (dateTime.Kind == DateTimeKind.Utc || dateTime.Kind == DateTimeKind.Local) { return new DateTimeOffset(dateTime.ToUniversalTime()).ToOffset(timeZone.BaseUtcOffset); } DateTimeOffset dateTimeOffset = new DateTimeOffset(dateTime, timeZone.GetUtcOffset(dateTime)); return dateTimeOffset.ToUniversalTime().ToOffset(timeZone.BaseUtcOffset); default: if (type == typeof(char[])) { return new String(value as char[]); } else if (type == typeof(XElement)) { return ((XElement)value).ToString(); } else if (type == typeof(Binary)) { return ((Binary)value).ToArray(); } break; } } return value; }
/// <summary> /// Converts the given DateTimeOffset value to string appropriate for Atom format. /// </summary> /// <param name="dateTime">Given DateTimeOffset value.</param> /// <returns>Atom format string representation of <paramref name="dateTime"/>.</returns> internal static string ToString(DateTimeOffset dateTime) { DebugUtils.CheckNoExternalCallers(); if (dateTime.Offset == zeroOffset) { return dateTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture); } return dateTime.ToString("yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture); }
/// <summary> /// Returns an enumerable collection of log blobs containing Analytics log records. The blobs are retrieved lazily. /// </summary> /// <param name="service">A <see cref="StorageService"/> enumeration value.</param> /// <param name="startTime">A <see cref="DateTimeOffset"/> object representing the start of the time range for which logs should be retrieved.</param> /// <param name="endTime">A <see cref="DateTimeOffset"/> object representing the end of the time range for which logs should be retrieved.</param> /// <param name="operations">A <see cref="LoggingOperations"/> enumeration value that indicates the types of logging operations on which to filter the log blobs.</param> /// <param name="details">A <see cref="BlobListingDetails"/> enumeration value that indicates whether or not blob metadata should be returned. Only <c>None</c> and <c>Metadata</c> are valid values. </param> /// <param name="options">A <see cref="BlobRequestOptions"/> object that specifies additional options for the request.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param> /// <returns>An enumerable collection of objects that implement <see cref="ICloudBlob"/> and are retrieved lazily.</returns> /// <remarks>Note that specifying a logging operation type for the <paramref name="operations"/> parameter will return any Analytics log blob that contains the specified logging operation, /// even if that log blob also includes other types of logging operations. Also note that the only currently supported values for the <paramref name="details"/> /// parameter are <c>None</c> and <c>Metadata</c>.</remarks> public IEnumerable<ICloudBlob> ListLogs(StorageService service, DateTimeOffset startTime, DateTimeOffset? endTime, LoggingOperations operations, BlobListingDetails details, BlobRequestOptions options, OperationContext operationContext) { CloudBlobDirectory logDirectory = this.GetLogDirectory(service); BlobListingDetails metadataDetails = details; DateTimeOffset utcStartTime = startTime.ToUniversalTime(); DateTimeOffset dateCounter = new DateTimeOffset(utcStartTime.Ticks - (utcStartTime.Ticks % TimeSpan.TicksPerHour), utcStartTime.Offset); DateTimeOffset? utcEndTime = null; string endPrefix = null; // Ensure that the date range is correct. if (endTime.HasValue) { utcEndTime = endTime.Value.ToUniversalTime(); endPrefix = logDirectory.Prefix + utcEndTime.Value.ToString("yyyy/MM/dd/HH", CultureInfo.InvariantCulture); if (utcStartTime > utcEndTime.Value) { string errorString = string.Format(CultureInfo.InvariantCulture, SR.StartTimeExceedsEndTime, startTime, endTime.Value); throw new ArgumentException(errorString); } } // Currently only support the ability to retrieve metadata on logs. if (details.HasFlag(BlobListingDetails.Copy) || details.HasFlag(BlobListingDetails.Snapshots) || details.HasFlag(BlobListingDetails.UncommittedBlobs)) { throw new ArgumentException(SR.InvalidListingDetails); } // At least one LogType must be specified. if (operations == LoggingOperations.None) { throw new ArgumentException(SR.InvalidLoggingLevel); } // If metadata or a specific LogType is specified, metadata should be retrieved. if (details.HasFlag(BlobListingDetails.Metadata) || !operations.HasFlag(LoggingOperations.All)) { metadataDetails = BlobListingDetails.Metadata; } // Check logs using an hour-based prefix until we reach a day boundary. while (dateCounter.Hour > 0) { string currentPrefix = logDirectory.Prefix + dateCounter.ToString("yyyy/MM/dd/HH", CultureInfo.InvariantCulture); IEnumerable<IListBlobItem> currentLogs = logDirectory.Container.ListBlobs(currentPrefix, true, metadataDetails, options, operationContext); foreach (ICloudBlob log in currentLogs) { if (!utcEndTime.HasValue || string.Compare(log.Parent.Prefix, endPrefix) <= 0) { if (IsCorrectLogType(log, operations)) { yield return log; } } else { yield break; } } dateCounter = dateCounter.AddHours(1); if (dateCounter > DateTimeOffset.UtcNow.AddHours(1)) { yield break; } } // Check logs using a day-based prefix until we reach a month boundary. while (dateCounter.Day > 1) { string currentPrefix = logDirectory.Prefix + dateCounter.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture); IEnumerable<IListBlobItem> currentLogs = logDirectory.Container.ListBlobs(currentPrefix, true, metadataDetails, options, operationContext); foreach (ICloudBlob log in currentLogs) { if (!utcEndTime.HasValue || string.Compare(log.Parent.Prefix, endPrefix) <= 0) { if (IsCorrectLogType(log, operations)) { yield return log; } } else { yield break; } } dateCounter = dateCounter.AddDays(1); if (dateCounter > DateTimeOffset.UtcNow.AddHours(1)) { yield break; } } // Check logs using a month-based prefix until we reach a year boundary. while (dateCounter.Month > 1) { string currentPrefix = logDirectory.Prefix + dateCounter.ToString("yyyy/MM", CultureInfo.InvariantCulture); IEnumerable<IListBlobItem> currentLogs = logDirectory.Container.ListBlobs(currentPrefix, true, metadataDetails, options, operationContext); foreach (ICloudBlob log in currentLogs) { if (!utcEndTime.HasValue || string.Compare(log.Parent.Prefix, endPrefix) <= 0) { if (IsCorrectLogType(log, operations)) { yield return log; } } else { yield break; } } dateCounter = dateCounter.AddMonths(1); if (dateCounter > DateTimeOffset.UtcNow.AddHours(1)) { yield break; } } // Continue using a year-based prefix. while (true) { string currentPrefix = logDirectory.Prefix + dateCounter.ToString("yyyy", CultureInfo.InvariantCulture); IEnumerable<IListBlobItem> currentLogs = logDirectory.Container.ListBlobs(currentPrefix, true, metadataDetails, options, operationContext); foreach (ICloudBlob log in currentLogs) { if (!utcEndTime.HasValue || string.Compare(log.Parent.Prefix, endPrefix) <= 0) { if (IsCorrectLogType(log, operations)) { yield return log; } } else { yield break; } } dateCounter = dateCounter.AddYears(1); if (dateCounter > DateTimeOffset.UtcNow.AddHours(1)) { yield break; } } }
private async void FillEntryItemFromXmlRss(FeedEntryItem entItem, XmlNode entryNode, XmlNamespaceManager NsMgr) { XmlNode entryTitle = entryNode.SelectSingleNode("title"); entItem.Name = (entryTitle != null) ? entryTitle.InnerText : ""; XmlNode entryId = entryNode.SelectSingleNode("guid"); entItem.EntryId = (entryId != null) ? entryId.InnerText : ""; XmlNode entryLinkUri = entryNode.SelectSingleNode("link"); try { if (entryLinkUri != null) { if (!string.IsNullOrEmpty(entryLinkUri.InnerText)) { entItem.AltHtmlUri = new Uri(entryLinkUri.InnerText); } } } catch (Exception e) { ToDebugWindow(">> Exception @FeedClient@FillEntryItemFromXmlRss:new Uri()" + Environment.NewLine + "RSS feed entry (" + entItem.Name + ") contain invalid entry Uri: " + e.Message + Environment.NewLine); } if (string.IsNullOrEmpty(entItem.EntryId)) { if (entItem.AltHtmlUri != null) { entItem.EntryId = entItem.AltHtmlUri.AbsoluteUri; } } XmlNode entryPudDate = entryNode.SelectSingleNode("pubDate"); if (entryPudDate != null) { string s = entryPudDate.InnerText; if (!string.IsNullOrEmpty(s)) { try { DateTimeOffset dtf = DateTimeParser.ParseDateTimeRFC822(s); entItem.Published = dtf.ToUniversalTime().DateTime; } catch (Exception e) { // Debug.WriteLine("Exception @ParseDateTimeRFC822 in the RSS 2.0 feed " + "("+ entItem.Name + ")" + " : " + e.Message); ToDebugWindow(">> Exception @FeedClient@FillEntryItemFromXmlRss:ParseDateTimeRFC822()" + Environment.NewLine + "RSS feed entry(" + entItem.Name + ") contain invalid entry pubDate (DateTimeRFC822 expected): " + e.Message + Environment.NewLine); // TODO: really shouldn't to cover these invalid format, but...for the usability stand point... try { DateTime tmp; if (DateTime.TryParse(s, out tmp)) { entItem.Published = tmp.ToUniversalTime(); } } catch { } } } } string entryAuthor = ""; XmlNodeList entryAuthors = entryNode.SelectNodes("dc:creator", NsMgr); if (entryAuthors != null) { foreach (XmlNode auth in entryAuthors) { if (string.IsNullOrEmpty(entryAuthor)) { entryAuthor = auth.InnerText; } else { entryAuthor += "/" + auth.InnerText; } } } if (string.IsNullOrEmpty(entryAuthor)) { if (entItem.AltHtmlUri != null) { entryAuthor = entItem.AltHtmlUri.Host; } } entItem.Author = entryAuthor; // gets imageUri from enclosure XmlNode enclosure = entryNode.SelectSingleNode("enclosure"); if (enclosure != null) { if (enclosure.Attributes["url"] != null) { string urlImage = enclosure.Attributes["url"].Value; if (enclosure.Attributes["type"] != null) { string imageType = enclosure.Attributes["type"].Value; if ((imageType == "image/jpg") || (imageType == "image/jpeg") || (imageType == "image/png") || (imageType == "image/gif")) { try { entItem.ImageUri = new Uri(urlImage); } catch (Exception e) { ToDebugWindow(">> Exception @FeedClient@FillEntryItemFromXmlRss:new Uri()" + Environment.NewLine + "RSS feed entry (" + entItem.Name + ") contain invalid entry > enclosure@link Uri: " + e.Message + Environment.NewLine); } } } } } // Force textHtml for RSS feed. Even though description was missing. (needs this for browser) entItem.ContentType = EntryItem.ContentTypes.textHtml; XmlNode sum = entryNode.SelectSingleNode("description"); if (sum != null) { // Content entItem.Content = await StripStyleAttributes(sum.InnerText); if (!string.IsNullOrEmpty(entItem.Content)) { // Summary entItem.Summary = await StripHtmlTags(entItem.Content); //entItem.Summary = Truncate(entItem.Summary, 230); //entItem.SummaryPlainText = Truncate(entItem.Summary, 78); // gets image Uri if (entItem.ImageUri == null) { entItem.ImageUri = await GetImageUriFromHtml(entItem.Content); } } } entItem.Status = FeedEntryItem.ReadStatus.rsNew; }
/// <summary> /// Returns an enumerable collection of log blobs containing Analytics log records. The blobs are retrieved lazily. /// </summary> /// <param name="service">A <see cref="StorageService"/> enumeration value.</param> /// <param name="startTime">A <see cref="DateTimeOffset"/> object representing the start of the time range for which logs should be retrieved.</param> /// <param name="endTime">A <see cref="DateTimeOffset"/> object representing the end of the time range for which logs should be retrieved.</param> /// <param name="operations">A <see cref="LoggingOperations"/> enumeration value that indicates the types of logging operations on which to filter the log blobs.</param> /// <param name="details">A <see cref="BlobListingDetails"/> enumeration value that indicates whether or not blob metadata should be returned. Only <c>None</c> and <c>Metadata</c> are valid values. </param> /// <param name="options">A <see cref="BlobRequestOptions"/> object that specifies additional options for the request.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param> /// <returns>An enumerable collection of objects that implement <see cref="ICloudBlob"/> and are retrieved lazily.</returns> /// <remarks>Note that specifying a logging operation type for the <paramref name="operations"/> parameter will return any Analytics log blob that contains the specified logging operation, /// even if that log blob also includes other types of logging operations. Also note that the only currently supported values for the <paramref name="details"/> /// parameter are <c>None</c> and <c>Metadata</c>.</remarks> public IEnumerable <ICloudBlob> ListLogs(StorageService service, DateTimeOffset startTime, DateTimeOffset?endTime, LoggingOperations operations, BlobListingDetails details, BlobRequestOptions options, OperationContext operationContext) { CloudBlobDirectory logDirectory = this.GetLogDirectory(service); BlobListingDetails metadataDetails = details; DateTimeOffset utcStartTime = startTime.ToUniversalTime(); DateTimeOffset dateCounter = new DateTimeOffset(utcStartTime.Ticks - (utcStartTime.Ticks % TimeSpan.TicksPerHour), utcStartTime.Offset); DateTimeOffset? utcEndTime = null; string endPrefix = null; // Ensure that the date range is correct. if (endTime.HasValue) { utcEndTime = endTime.Value.ToUniversalTime(); endPrefix = logDirectory.Prefix + utcEndTime.Value.ToString("yyyy/MM/dd/HH", CultureInfo.InvariantCulture); if (utcStartTime > utcEndTime.Value) { string errorString = string.Format(CultureInfo.InvariantCulture, SR.StartTimeExceedsEndTime, startTime, endTime.Value); throw new ArgumentException(errorString); } } // Currently only support the ability to retrieve metadata on logs. if (details.HasFlag(BlobListingDetails.Copy) || details.HasFlag(BlobListingDetails.Snapshots) || details.HasFlag(BlobListingDetails.UncommittedBlobs)) { throw new ArgumentException(SR.InvalidListingDetails); } // At least one LogType must be specified. if (operations == LoggingOperations.None) { throw new ArgumentException(SR.InvalidLoggingLevel); } // If metadata or a specific LogType is specified, metadata should be retrieved. if (details.HasFlag(BlobListingDetails.Metadata) || !operations.HasFlag(LoggingOperations.All)) { metadataDetails = BlobListingDetails.Metadata; } // Check logs using an hour-based prefix until we reach a day boundary. while (dateCounter.Hour > 0) { string currentPrefix = logDirectory.Prefix + dateCounter.ToString("yyyy/MM/dd/HH", CultureInfo.InvariantCulture); IEnumerable <IListBlobItem> currentLogs = logDirectory.Container.ListBlobs(currentPrefix, true, metadataDetails, options, operationContext); foreach (ICloudBlob log in currentLogs) { if (!utcEndTime.HasValue || string.Compare(log.Parent.Prefix, endPrefix) <= 0) { if (IsCorrectLogType(log, operations)) { yield return(log); } } else { yield break; } } dateCounter = dateCounter.AddHours(1); if (dateCounter > DateTimeOffset.UtcNow.AddHours(1)) { yield break; } } // Check logs using a day-based prefix until we reach a month boundary. while (dateCounter.Day > 1) { string currentPrefix = logDirectory.Prefix + dateCounter.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture); IEnumerable <IListBlobItem> currentLogs = logDirectory.Container.ListBlobs(currentPrefix, true, metadataDetails, options, operationContext); foreach (ICloudBlob log in currentLogs) { if (!utcEndTime.HasValue || string.Compare(log.Parent.Prefix, endPrefix) <= 0) { if (IsCorrectLogType(log, operations)) { yield return(log); } } else { yield break; } } dateCounter = dateCounter.AddDays(1); if (dateCounter > DateTimeOffset.UtcNow.AddHours(1)) { yield break; } } // Check logs using a month-based prefix until we reach a year boundary. while (dateCounter.Month > 1) { string currentPrefix = logDirectory.Prefix + dateCounter.ToString("yyyy/MM", CultureInfo.InvariantCulture); IEnumerable <IListBlobItem> currentLogs = logDirectory.Container.ListBlobs(currentPrefix, true, metadataDetails, options, operationContext); foreach (ICloudBlob log in currentLogs) { if (!utcEndTime.HasValue || string.Compare(log.Parent.Prefix, endPrefix) <= 0) { if (IsCorrectLogType(log, operations)) { yield return(log); } } else { yield break; } } dateCounter = dateCounter.AddMonths(1); if (dateCounter > DateTimeOffset.UtcNow.AddHours(1)) { yield break; } } // Continue using a year-based prefix. while (true) { string currentPrefix = logDirectory.Prefix + dateCounter.ToString("yyyy", CultureInfo.InvariantCulture); IEnumerable <IListBlobItem> currentLogs = logDirectory.Container.ListBlobs(currentPrefix, true, metadataDetails, options, operationContext); foreach (ICloudBlob log in currentLogs) { if (!utcEndTime.HasValue || string.Compare(log.Parent.Prefix, endPrefix) <= 0) { if (IsCorrectLogType(log, operations)) { yield return(log); } } else { yield break; } } dateCounter = dateCounter.AddYears(1); if (dateCounter > DateTimeOffset.UtcNow.AddHours(1)) { yield break; } } }
internal static TimeSpan GetUnixTimestamp(this DateTimeOffset dateTimeOffset) { return(dateTimeOffset.ToUniversalTime().Subtract(_epochDateTimeOffset)); }
private static async Task CreatePreflightPlanAsync(GraphService graphClient, string groupId, string channelId, DateTimeOffset departureTime) { // Create a "Pre-flight checklist" plan var preFlightCheckList = new Plan { Title = "Pre-flight Checklist", Owner = groupId }; var createdPlan = await graphClient.CreatePlanAsync(preFlightCheckList); logger.Info("Create plan"); // Create buckets var toDoBucket = new Bucket { Name = "To Do", PlanId = createdPlan.Id }; var createdToDoBucket = await graphClient.CreateBucketAsync(toDoBucket); var completedBucket = new Bucket { Name = "Completed", PlanId = createdPlan.Id }; var createdCompletedBucket = await graphClient.CreateBucketAsync(completedBucket); // Create tasks in to-do bucket var preFlightInspection = new PlannerTask { Title = "Perform pre-flight inspection of aircraft", PlanId = createdPlan.Id, BucketId = createdToDoBucket.Id, DueDateTime = departureTime.ToUniversalTime() }; await graphClient.CreatePlannerTaskAsync(preFlightInspection); var ensureFoodBevStock = new PlannerTask { Title = "Ensure food and beverages are fully stocked", PlanId = createdPlan.Id, BucketId = createdToDoBucket.Id, DueDateTime = departureTime.ToUniversalTime() }; await graphClient.CreatePlannerTaskAsync(ensureFoodBevStock); if (createTabs) { // Add planner tab to General channel var plannerTab = new TeamsChannelTab { Name = "Pre-flight Checklist", TeamsAppId = "com.microsoft.teamspace.tab.planner", Configuration = new TeamsChannelTabConfiguration { EntityId = createdPlan.Id, ContentUrl = $"https://tasks.office.com/{tenantName}/Home/PlannerFrame?page=7&planId={createdPlan.Id}&auth_pvr=Orgid&auth_upn={{upn}}&mkt={{locale}}", RemoveUrl = $"https://tasks.office.com/{tenantName}/Home/PlannerFrame?page=13&planId={createdPlan.Id}&auth_pvr=Orgid&auth_upn={{upn}}&mkt={{locale}}", WebsiteUrl = $"https://tasks.office.com/{tenantName}/Home/PlanViews/{createdPlan.Id}" } }; await graphClient.AddTeamChannelTab(groupId, channelId, plannerTab); } }
public void TimestampTz() { using (var conn = OpenConnection()) { var tzOffset = TimeZoneInfo.Local.BaseUtcOffset; if (tzOffset == TimeSpan.Zero) { Assert.Ignore("Test cannot run when machine timezone is UTC"); } var dateTimeUtc = new DateTime(2015, 6, 27, 8, 45, 12, 345, DateTimeKind.Utc); var dateTimeLocal = dateTimeUtc.ToLocalTime(); var dateTimeUnspecified = new DateTime(dateTimeUtc.Ticks, DateTimeKind.Unspecified); var nDateTimeUtc = new NpgsqlDateTime(dateTimeUtc); var nDateTimeLocal = nDateTimeUtc.ToLocalTime(); var nDateTimeUnspecified = new NpgsqlDateTime(nDateTimeUtc.Ticks, DateTimeKind.Unspecified); var dateTimeOffset = new DateTimeOffset(dateTimeLocal, dateTimeLocal - dateTimeUtc); using (var cmd = new NpgsqlCommand("SELECT @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9", conn)) { cmd.Parameters.AddWithValue("p1", NpgsqlDbType.TimestampTZ, dateTimeUtc); cmd.Parameters.AddWithValue("p2", NpgsqlDbType.TimestampTZ, dateTimeLocal); cmd.Parameters.AddWithValue("p3", NpgsqlDbType.TimestampTZ, dateTimeUnspecified); cmd.Parameters.AddWithValue("p4", NpgsqlDbType.TimestampTZ, nDateTimeUtc); cmd.Parameters.AddWithValue("p5", NpgsqlDbType.TimestampTZ, nDateTimeLocal); cmd.Parameters.AddWithValue("p6", NpgsqlDbType.TimestampTZ, nDateTimeUnspecified); cmd.Parameters.AddWithValue("p7", dateTimeUtc); Assert.That(cmd.Parameters["p7"].NpgsqlDbType, Is.EqualTo(NpgsqlDbType.TimestampTZ)); cmd.Parameters.AddWithValue("p8", nDateTimeUtc); Assert.That(cmd.Parameters["p8"].NpgsqlDbType, Is.EqualTo(NpgsqlDbType.TimestampTZ)); cmd.Parameters.AddWithValue("p9", dateTimeOffset); Assert.That(cmd.Parameters["p9"].NpgsqlDbType, Is.EqualTo(NpgsqlDbType.TimestampTZ)); using (var reader = cmd.ExecuteReader()) { reader.Read(); for (var i = 0; i < cmd.Parameters.Count; i++) { // Regular type (DateTime) Assert.That(reader.GetFieldType(i), Is.EqualTo(typeof(DateTime))); Assert.That(reader.GetDateTime(i), Is.EqualTo(dateTimeLocal)); Assert.That(reader.GetFieldValue <DateTime>(i).Kind, Is.EqualTo(DateTimeKind.Local)); Assert.That(reader[i], Is.EqualTo(dateTimeLocal)); Assert.That(reader.GetValue(i), Is.EqualTo(dateTimeLocal)); // Provider-specific type (NpgsqlDateTime) Assert.That(reader.GetTimeStamp(i), Is.EqualTo(nDateTimeLocal)); Assert.That(reader.GetProviderSpecificFieldType(i), Is.EqualTo(typeof(NpgsqlDateTime))); Assert.That(reader.GetProviderSpecificValue(i), Is.EqualTo(nDateTimeLocal)); Assert.That(reader.GetFieldValue <NpgsqlDateTime>(i), Is.EqualTo(nDateTimeLocal)); // DateTimeOffset Assert.That(reader.GetFieldValue <DateTimeOffset>(i), Is.EqualTo(dateTimeOffset.ToUniversalTime())); } } } Assert.AreEqual(nDateTimeUtc, nDateTimeLocal.ToUniversalTime()); Assert.AreEqual(nDateTimeUtc, new NpgsqlDateTime(nDateTimeLocal.Ticks, DateTimeKind.Unspecified).ToUniversalTime()); Assert.AreEqual(nDateTimeLocal, nDateTimeUnspecified.ToLocalTime()); } }
private static long ComputeTotpRemainingSeconds(this DateTimeOffset time, long period) { return(period - (time.ToUniversalTime().ToUnixTimeSeconds() - InitialCounterTime) % period); }
public static double DateTimeOffsetToUnixTimestamp(DateTimeOffset dateTime) { DateTimeOffset unixStart = new DateTimeOffset(1970, 1, 1, 0, 0, 0, 0, new TimeSpan(0, 0, 0)); long unixTimeStampInTicks = (dateTime.ToUniversalTime() - unixStart).Ticks; return (double)unixTimeStampInTicks / TimeSpan.TicksPerSecond; }
public static object ConvertPrimitiveValue(object value, Type type) { Contract.Assert(value != null); Contract.Assert(type != null); // if value is of the same type nothing to do here. if (value.GetType() == type || value.GetType() == Nullable.GetUnderlyingType(type)) { return(value); } string str = value as string; if (type == typeof(char)) { if (str == null || str.Length != 1) { throw new ValidationException(Error.Format(SRResources.PropertyMustBeStringLengthOne)); } return(str[0]); } else if (type == typeof(char?)) { if (str == null || str.Length > 1) { throw new ValidationException(Error.Format(SRResources.PropertyMustBeStringMaxLengthOne)); } return(str.Length > 0 ? str[0] : (char?)null); } else if (type == typeof(char[])) { if (str == null) { throw new ValidationException(Error.Format(SRResources.PropertyMustBeString)); } return(str.ToCharArray()); } // TODO: Binary not supported //else if (type == typeof(Binary)) //{ // return new Binary((byte[])value); //} else if (type == typeof(XElement)) { if (str == null) { throw new ValidationException(Error.Format(SRResources.PropertyMustBeString)); } return(XElement.Parse(str)); } else { type = Nullable.GetUnderlyingType(type) ?? type; if (type.GetTypeInfo().IsEnum) { if (str == null) { throw new ValidationException(Error.Format(SRResources.PropertyMustBeString)); } return(Enum.Parse(type, str)); } else if (type == typeof(DateTime)) { if (value is DateTimeOffset) { DateTimeOffset dateTimeOffsetValue = (DateTimeOffset)value; TimeZoneInfo timeZone = TimeZoneInfoHelper.TimeZone; dateTimeOffsetValue = dateTimeOffsetValue.ToUniversalTime().ToOffset(timeZone.BaseUtcOffset); return(dateTimeOffsetValue.DateTime); } throw new ValidationException(Error.Format(SRResources.PropertyMustBeDateTimeOffset)); } else { Contract.Assert(type == typeof(uint) || type == typeof(ushort) || type == typeof(ulong)); // Note that we are not casting the return value to nullable<T> as even if we do it // CLR would unbox it back to T. return(Convert.ChangeType(value, type, CultureInfo.InvariantCulture)); } } }
internal static string DateToString(DateTimeOffset dateTime) { // Format according to RFC1123; 'r' uses invariant info (DateTimeFormatInfo.InvariantInfo). return(dateTime.ToUniversalTime().ToString("r", CultureInfo.InvariantCulture)); }
// T-REC-X.680-201508 sec 46 // T-REC-X.690-201508 sec 11.7 private void WriteGeneralizedTimeCore( Asn1Tag tag, DateTimeOffset value, bool omitFractionalSeconds) { // GeneralizedTime under BER allows many different options: // * (HHmmss), (HHmm), (HH) // * "(value).frac", "(value),frac" // * frac == 0 may be omitted or emitted // non-UTC offset in various formats // // We're not allowing any of them. // Just encode as the CER/DER common restrictions. // // This results in the following formats: // yyyyMMddHHmmssZ // yyyyMMddHHmmss.f?Z // // where "f?" is anything from "f" to "fffffff" (tenth of a second down to 100ns/1-tick) // with no trailing zeros. DateTimeOffset normalized = value.ToUniversalTime(); if (normalized.Year > 9999) { // This is unreachable since DateTimeOffset guards against this internally. throw new ArgumentOutOfRangeException(nameof(value)); } // We're only loading in sub-second ticks. // Ticks are defined as 1e-7 seconds, so their printed form // is at the longest "0.1234567", or 9 bytes. Span <byte> fraction = stackalloc byte[0]; if (!omitFractionalSeconds) { long floatingTicks = normalized.Ticks % TimeSpan.TicksPerSecond; if (floatingTicks != 0) { // We're only loading in sub-second ticks. // Ticks are defined as 1e-7 seconds, so their printed form // is at the longest "0.1234567", or 9 bytes. fraction = stackalloc byte[9]; decimal decimalTicks = floatingTicks; decimalTicks /= TimeSpan.TicksPerSecond; if (!Utf8Formatter.TryFormat(decimalTicks, fraction, out int bytesWritten, new StandardFormat('G'))) { Debug.Fail($"Utf8Formatter.TryFormat could not format {floatingTicks} / TicksPerSecond"); throw new InvalidOperationException(); } Debug.Assert(bytesWritten > 2, $"{bytesWritten} should be > 2"); Debug.Assert(fraction[0] == (byte)'0'); Debug.Assert(fraction[1] == (byte)'.'); fraction = fraction.Slice(1, bytesWritten - 1); } } // yyyy, MM, dd, hh, mm, ss const int IntegerPortionLength = 4 + 2 + 2 + 2 + 2 + 2; // Z, and the optional fraction. int totalLength = IntegerPortionLength + 1 + fraction.Length; // Because GeneralizedTime is IMPLICIT VisibleString it technically can have // a constructed form. // DER says character strings must be primitive. // CER says character strings <= 1000 encoded bytes must be primitive. // So we'll just make BER be primitive, too. Debug.Assert(!tag.IsConstructed); WriteTag(tag); WriteLength(totalLength); int year = normalized.Year; int month = normalized.Month; int day = normalized.Day; int hour = normalized.Hour; int minute = normalized.Minute; int second = normalized.Second; Span <byte> baseSpan = _buffer.AsSpan(_offset); StandardFormat d4 = new StandardFormat('D', 4); StandardFormat d2 = new StandardFormat('D', 2); if (!Utf8Formatter.TryFormat(year, baseSpan.Slice(0, 4), out _, d4) || !Utf8Formatter.TryFormat(month, baseSpan.Slice(4, 2), out _, d2) || !Utf8Formatter.TryFormat(day, baseSpan.Slice(6, 2), out _, d2) || !Utf8Formatter.TryFormat(hour, baseSpan.Slice(8, 2), out _, d2) || !Utf8Formatter.TryFormat(minute, baseSpan.Slice(10, 2), out _, d2) || !Utf8Formatter.TryFormat(second, baseSpan.Slice(12, 2), out _, d2)) { Debug.Fail($"Utf8Formatter.TryFormat failed to build components of {normalized:O}"); throw new InvalidOperationException(); } _offset += IntegerPortionLength; fraction.CopyTo(baseSpan.Slice(IntegerPortionLength)); _offset += fraction.Length; _buffer[_offset] = (byte)'Z'; _offset++; }
internal static long ToUnixTime(this DateTimeOffset datetime) { return((long)datetime.ToUniversalTime().Subtract(UnixEpochDateTimeOffset).TotalSeconds); }
string RangeFormat() { return(string.Format("TABLE_DATE_RANGE({0}, TIMESTAMP('{1}'), TIMESTAMP('{2}'))", prefix, timestampFrom.ToUniversalTime().ToString("yyyy-MM-dd"), timestampTo.ToUniversalTime().ToString("yyyy-MM-dd"))); }
public static double ToUnixTimestamp(this DateTimeOffset d) { var duration = d.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0); return(duration.TotalSeconds); }
// TODO: Note, this enables comparisons between values that did or did not have timezones, need to fix. private DateTimeOffset toComparable() => _parsedValue.ToUniversalTime();
/// <summary> /// Converts a DateTimeOffset object to unix time. /// </summary> /// <param name="dateTime">The date time.</param> /// <returns>The unix date time.</returns> public static double ToUnixTime(DateTimeOffset dateTime) { return((dateTime.ToUniversalTime() - Epoch).TotalSeconds); }
/// <summary> /// Returns the next time at which the <see cref="IDailyTimeIntervalTrigger" /> will /// fire, after the given time. If the trigger will not fire after the given /// time, <see langword="null" /> will be returned. /// </summary> /// <param name="afterTime"></param> /// <returns></returns> public override DateTimeOffset?GetFireTimeAfter(DateTimeOffset?afterTime) { // Check if trigger has completed or not. if (complete) { return(null); } // Check repeatCount limit if (repeatCount != RepeatIndefinitely && timesTriggered > repeatCount) { return(null); } // a. Increment afterTime by a second, so that we are comparing against a time after it! if (afterTime == null) { afterTime = SystemTime.UtcNow().AddSeconds(1); } else { afterTime = afterTime.Value.AddSeconds(1); } // make sure afterTime is at least startTime if (afterTime < startTimeUtc) { afterTime = startTimeUtc; } // now change to local time zone afterTime = TimeZoneUtil.ConvertTime(afterTime.Value, TimeZone); // b.Check to see if afterTime is after endTimeOfDay or not. // If yes, then we need to advance to next day as well. bool afterTimePastEndTimeOfDay = false; if (endTimeOfDay != null) { afterTimePastEndTimeOfDay = afterTime.Value > endTimeOfDay.GetTimeOfDayForDate(afterTime).Value; } // c. now we need to move to the next valid day of week if either: // the given time is past the end time of day, or given time is not on a valid day of week DateTimeOffset?fireTime = AdvanceToNextDayOfWeekIfNecessary(afterTime.Value, afterTimePastEndTimeOfDay); if (fireTime == null) { return(null); } // apply timezone for this date & time fireTime = new DateTimeOffset(fireTime.Value.DateTime, TimeZoneUtil.GetUtcOffset(fireTime.Value, TimeZone)); // d. Calculate and save fireTimeEndDate variable for later use DateTimeOffset fireTimeEndDate; if (endTimeOfDay == null) { fireTimeEndDate = new TimeOfDay(23, 59, 59).GetTimeOfDayForDate(fireTime).Value; } else { fireTimeEndDate = endTimeOfDay.GetTimeOfDayForDate(fireTime).Value; } // apply the proper offset for the end date fireTimeEndDate = new DateTimeOffset(fireTimeEndDate.DateTime, TimeZoneUtil.GetUtcOffset(fireTimeEndDate.DateTime, this.TimeZone)); // e. Check fireTime against startTime or startTimeOfDay to see which go first. DateTimeOffset fireTimeStartDate = startTimeOfDay.GetTimeOfDayForDate(fireTime).Value; // apply the proper offset for the start date fireTimeStartDate = new DateTimeOffset(fireTimeStartDate.DateTime, TimeZoneUtil.GetUtcOffset(fireTimeStartDate.DateTime, this.TimeZone)); if (fireTime < fireTimeStartDate) { return(fireTimeStartDate.ToUniversalTime()); } // f. Continue to calculate the fireTime by incremental unit of intervals. // recall that if fireTime was less that fireTimeStartDate, we didn't get this far startTimeUtc = TimeZoneUtil.ConvertTime(fireTimeStartDate, TimeZone); long secondsAfterStart = (long)(fireTime.Value - startTimeUtc).TotalSeconds; long repeatLong = RepeatInterval; DateTimeOffset sTime = fireTimeStartDate; IntervalUnit repeatUnit = RepeatIntervalUnit; if (repeatUnit == IntervalUnit.Second) { long jumpCount = secondsAfterStart / repeatLong; if (secondsAfterStart % repeatLong != 0) { jumpCount++; } sTime = sTime.AddSeconds(RepeatInterval * (int)jumpCount); fireTime = sTime; } else if (repeatUnit == IntervalUnit.Minute) { long jumpCount = secondsAfterStart / (repeatLong * 60L); if (secondsAfterStart % (repeatLong * 60L) != 0) { jumpCount++; } sTime = sTime.AddMinutes(RepeatInterval * (int)jumpCount); fireTime = sTime; } else if (repeatUnit == IntervalUnit.Hour) { long jumpCount = secondsAfterStart / (repeatLong * 60L * 60L); if (secondsAfterStart % (repeatLong * 60L * 60L) != 0) { jumpCount++; } sTime = sTime.AddHours(RepeatInterval * (int)jumpCount); fireTime = sTime; } // g. Ensure this new fireTime is within the day, or else we need to advance to next day. if (fireTime > fireTimeEndDate) { fireTime = AdvanceToNextDayOfWeekIfNecessary(fireTime.Value, IsSameDay(fireTime.Value, fireTimeEndDate)); // make sure we hit the startTimeOfDay on the new day fireTime = startTimeOfDay.GetTimeOfDayForDate(fireTime); } // i. Return calculated fireTime. if (fireTime == null) { return(null); } // apply proper offset var d = fireTime.Value; d = new DateTimeOffset(d.DateTime, TimeZoneUtil.GetUtcOffset(d.DateTime, this.TimeZone)); return(d.ToUniversalTime()); }
/// <summary> /// Get this datetime as a Unix epoch timestamp (seconds since Jan 1, 1970, midnight UTC). /// </summary> /// <param name="date">The date to convert.</param> /// <returns>Seconds since Unix epoch.</returns> public static long ToLong(DateTimeOffset date) => (long)Math.Round((date.ToUniversalTime() - UnixEpoch).TotalSeconds);
private string FormatDateTime(DateTimeOffset dateTime) { return string.Format(CultureInfo.InvariantCulture, "{0:O}", dateTime.ToUniversalTime()); }
private string DateTimeOffsetToIso8601(DateTimeOffset dateTimeOffset) { var s = JsonConvert.SerializeObject(dateTimeOffset.ToUniversalTime()); return(s.Substring(1, s.Length - 2)); }
/// <summary> /// Converts a DateTimeOffset object to unix time. /// </summary> /// <param name="dateTime">The date time.</param> /// <returns>The unix date time.</returns> public static double ToUnixTime(DateTimeOffset dateTime) { Contract.Requires(dateTime >= Epoch); return (dateTime.ToUniversalTime() - Epoch).TotalSeconds; }
private string GetDateFilterAsString(APISearchTerm term, int offset) { string filter = ""; string not = ""; DateTime d1 = DateTime.UtcNow; DateTime d2 = DateTime.UtcNow; if (term.values.Count == 2) { d1 = DateTime.Parse(term.values[0], null, System.Globalization.DateTimeStyles.RoundtripKind); d2 = DateTime.Parse(term.values[1], null, System.Globalization.DateTimeStyles.RoundtripKind); } else { d1 = DateTime.Parse(term.values[0], null, System.Globalization.DateTimeStyles.RoundtripKind); } DateTimeOffset do1 = new DateTimeOffset(d1, new TimeSpan(offset, 0, 0)); DateTimeOffset do2 = new DateTimeOffset(d2, new TimeSpan(offset, 0, 0)); switch (term.op) { case APISearch.SearchComparer.between: if (term.values.Count == 2) { not = term.not ? "not" : ""; filter += $" ({term.field} {not} between '{do1.ToUniversalTime().ToString("yyyy/MM/dd HH:mm:ss")}' and '{do2.ToUniversalTime().ToString("yyyy/MM/dd HH:mm:ss")}' ) "; } break; case APISearch.SearchComparer.eq: not = term.not ? "<>" : "="; filter += $" ({term.field} {not} '{do1.ToUniversalTime().ToString("yyyy/MM/dd HH:mm:ss")}') "; break; case APISearch.SearchComparer.gt: not = term.not ? "<=" : ">"; filter += $" ({term.field} {not} '{do1.ToUniversalTime().ToString("yyyy/MM/dd HH:mm:ss")}') "; break; case APISearch.SearchComparer.gte: not = term.not ? "<" : ">="; filter += $" ({term.field} {not} '{do1.ToUniversalTime().ToString("yyyy/MM/dd HH:mm:ss")}') "; break; case APISearch.SearchComparer.lt: not = term.not ? ">=" : "<"; filter += $" ({term.field} {not} '{do1.ToUniversalTime().ToString("yyyy/MM/dd HH:mm:ss")}') "; break; case APISearch.SearchComparer.lte: not = term.not ? ">" : "<="; filter += $" ({term.field} {not} '{do1.ToUniversalTime().ToString("yyyy/MM/dd HH:mm:ss")}') "; break; } return(filter); }
/// <summary> /// Convert the value of the current <see cref="DateTimeOffset"/> object to universal time. /// </summary> /// <param name="DateTimeOffset"></param> /// <returns></returns> public static DateTimeOffset?ToUniversalTime(this DateTimeOffset?DateTimeOffset) { return(DateTimeOffset?.ToUniversalTime()); }
public void Complete(AvailabilityTelemetry availabilityResult) { using (_log.BeginScopeSafe(_logScope)) { _log?.LogInformation($"{nameof(AvailabilityTestScope)}.{nameof(Complete)} beginning:" + " {{TestDisplayName=\"{TestDisplayName}\", SpanId=\"{SpanId}\"}}", TestDisplayName, Format.SpellIfNull(_activitySpanId)); Validate.NotNull(availabilityResult, nameof(availabilityResult)); TransitionStage(from: Stage.Started, to: Stage.Completed); // Stop the timer: _endTime = DateTimeOffset.Now; // Stop activity: _activitySpan.Stop(); // Examine several properties of the Availability Result. // If the user set them, use the user's value. Otherwise, initialize appropriately: if (String.IsNullOrWhiteSpace(availabilityResult.Message)) { availabilityResult.Message = availabilityResult.Success ? DefaultResultMessage_NoError_Pass : DefaultResultMessage_NoError_Fail; } if (availabilityResult.Timestamp == default(DateTimeOffset)) { availabilityResult.Timestamp = _startTime; } else if (availabilityResult.Timestamp.ToUniversalTime() != _startTime.ToUniversalTime()) { _log?.LogDebug($"{nameof(AvailabilityTestScope)}.{nameof(Complete)} (SpanId=\"{{SpanId}}\") detected that the Timestamp of the" + $" specified Availability Result is different from the corresponding value of this {nameof(AvailabilityTestScope)}." + $" The value specified in the Availability Result takes precedence for tracking." + " AvailabilityTestScope_StartTime=\"{AvailabilityTestScope_StartTime}\". AvailabilityResult_Timestamp=\"{AvailabilityResult_Timestamp}\"", _activitySpanId, _startTime.ToUniversalTime().ToString("o"), availabilityResult.Timestamp.ToUniversalTime().ToString("o")); } TimeSpan duration = _endTime - availabilityResult.Timestamp; if (availabilityResult.Duration == TimeSpan.Zero) { availabilityResult.Duration = duration; } else if (availabilityResult.Duration != duration) { _log?.LogDebug($"{nameof(AvailabilityTestScope)}.{nameof(Complete)} (SpanId=\"{{SpanId}}\") detected that the Duration of the" + $" specified Availability Result is different from the corresponding value of this {nameof(AvailabilityTestScope)}." + $" The value specified in the Availability Result takes precedence for tracking." + " AvailabilityTestScope_Duration=\"{AvailabilityTestScope_Duration}\". AvailabilityResult_Duration=\"{AvailabilityResult_Duration}\"", _activitySpanId, duration, availabilityResult.Duration); } if (String.IsNullOrWhiteSpace(availabilityResult.Name)) { availabilityResult.Name = this.TestDisplayName; } else if (!availabilityResult.Name.Equals(TestDisplayName, StringComparison.Ordinal)) { _log?.LogDebug($"{nameof(AvailabilityTestScope)}.{nameof(Complete)} (SpanId=\"{{SpanId}}\") detected that the Name of the" + $" specified Availability Result is different from the corresponding value of this {nameof(AvailabilityTestScope)}." + $" The value specified in the Availability Result takes precedence for tracking." + " AvailabilityTestScopeTestDisplayName=\"{AvailabilityTestScope_TestDisplayName}\". AvailabilityResult_Name=\"{AvailabilityResult_Name}\"", _activitySpanId, TestDisplayName, availabilityResult.Name); } if (String.IsNullOrWhiteSpace(availabilityResult.RunLocation)) { availabilityResult.RunLocation = this.LocationDisplayName; } else if (!availabilityResult.RunLocation.Equals(LocationDisplayName, StringComparison.Ordinal)) { _log?.LogDebug($"{nameof(AvailabilityTestScope)}.{nameof(Complete)} (SpanId=\"{{SpanId}}\") detected that the RunLocation of the" + $" specified Availability Result is different from the corresponding value of this {nameof(AvailabilityTestScope)}." + $" The value specified in the Availability Result takes precedence for tracking." + " AvailabilityTestScope_LocationDisplayName=\"{AvailabilityTestScope_LocationDisplayName}\". AvailabilityResult_RunLocation=\"{AvailabilityResult_RunLocation}\"", _activitySpanId, LocationDisplayName, availabilityResult.RunLocation); } // The user may or may not have set the ID of the availability result telemetry. // Either way, we must set it to the right value, otherwise distributed tracing will break: availabilityResult.Id = _activitySpanId; // Similarly, whatever iKey the user set, we insist on the value from this scope's telemetry configuration to make // sure everything ends up in the right place. // Users may request a feature to allow sending availabuility results to an iKey that is different from other telemetry. // If so, we should consider exposing a corresponsing parameter on the ctor of this class and - corresponsingly - on // the AvailabilityTestResultAttribute. In that case we must also do the appropriate thing with the traces sent by this // class. Sending them and the telemetry result to different destinations may be a failure pit for the user. availabilityResult.Context.InstrumentationKey = _instrumentationKey; // Set custom SDK version to differentiate CAT tests from the regular availability telemetry availabilityResult.Context.GetInternalContext().SdkVersion = SdkVersion; // Store the result, but do not send it until SendResult() is called: _finalAvailabilityResult = availabilityResult; _log?.LogInformation($"{nameof(AvailabilityTestScope)}.{nameof(Complete)} finished" + " {{TestDisplayName=\"{TestDisplayName}\", " + " SpanId=\"{SpanId}\", StartTime=\"{StartTime}\", EndTime=\"{EndTime}\", Duration=\"{Duration}\", Success=\"{Success}\"}}", TestDisplayName, _activitySpanId, _startTime.ToString("o"), _endTime.ToString("o"), duration, availabilityResult.Success); } }
public void TestSerializeDateTimeOffset() { var value = new DateTimeOffset(new DateTime(2010, 10, 8, 11, 29, 0), TimeSpan.FromHours(-4)); var isoDate = value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFZ"); var obj = new TestClass { A = value, D = value, S = value }; var json = obj.ToJson(); var expected = "{ 'A' : #A, 'D' : #D, 'S' : '#S' }"; expected = expected.Replace("#A", string.Format("[NumberLong('{0}'), {1}]", value.DateTime.Ticks, value.Offset.TotalMinutes)); expected = expected.Replace("#D", "{ 'DateTime' : ISODate('#D'), 'Ticks' : NumberLong('#T'), 'Offset' : #O }" .Replace("#D", isoDate) .Replace("#T", value.DateTime.Ticks.ToString()) .Replace("#O", XmlConvert.ToString(value.Offset.TotalMinutes)) ); expected = expected.Replace("#S", "2010-10-08T11:29:00-04:00"); expected = expected.Replace("'", "\""); Assert.AreEqual(expected, json); var bson = obj.ToBson(); var rehydrated = BsonSerializer.Deserialize<TestClass>(bson); Assert.IsTrue(bson.SequenceEqual(rehydrated.ToBson())); }
public void FromStringSucceeds() { var start = new DateTimeOffset(2014, 5, 6, 5, 21, 42, 0, TimeSpan.FromHours(1)); var end = new DateTimeOffset(2015, 5, 6, 5, 21, 42, 0, TimeSpan.FromHours(1)); var iso8601DatePeriod = string.Concat(start.ToString("yyyy-MM-ddTHH:mm:sszzz"), "/", end.ToString("yyyy-MM-ddTHH:mm:sszzz")); var iso8601DatePeriodUtc = string.Concat(start.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:sszzz"), "/", end.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:sszzz"));; var sut = new DateTimeRange(iso8601DatePeriod); Assert.IsNotNull(sut); Assert.AreEqual(start, sut.Start); Assert.AreEqual(end, sut.End); Assert.AreEqual(end - start, sut.TimeSpan); var result = sut.ToString(); Assert.AreEqual(iso8601DatePeriodUtc, result); }
/// <summary> /// Convert specified <see cref="DateTimeOffset"/> to <see cref="Int64"/> as MessagePack defacto-standard. /// </summary> /// <param name="value"><see cref="DateTimeOffset"/>.</param> /// <returns> /// UTC epoc time from 1970/1/1 0:00:00, in milliseconds. /// </returns> public static long FromDateTimeOffset( DateTimeOffset value ) { return ( long )value.ToUniversalTime().Subtract( _unixEpocUtc ).TotalMilliseconds; }
/// <summary> /// Uses hash distribution to get all users which should /// receive a request at a specified minute of the day. /// </summary> /// <remarks> /// This will use a hash function to calculate all the minutes /// in a day for each user on which that user should receive a /// vlog record request. All users for which the specified /// <paramref name="time"/> minute matches any of their calculated /// minutes get returned. This also takes timezones into account. /// </remarks> /// <param name="time"><see cref="DateTimeOffset"/></param> /// <param name="offset"><see cref="TimeSpan"/></param> /// <returns><see cref="User"/> collection</returns> public virtual async IAsyncEnumerable <User> GetForMinuteAsync(DateTimeOffset time, TimeSpan?offset = null) { // Extract the current minute from the time parameter. var day = new DateTime(time.Year, time.Month, time.Day); var timeUtc = time.ToUniversalTime() + (offset ?? TimeSpan.Zero); var thisMinute = (timeUtc.Hour * 60) + timeUtc.Minute; // This call gets all users which are eligible for a vlog request, // meaning they have a vlog request limit greater than zero. await foreach (var user in _userService.GetAllVloggableUsersAsync(Navigation.All)) { var requestCount = Math.Min(_options.MaxDailyVlogRequestLimit, user.DailyVlogRequestLimit); if (requestCount <= 0) { continue; } // We store each discovered minute to compare them to each other, // making sure a minimum interval exists between them. The minimum // interval is only checked BEFORE the current minute, meaning the // first one of the two is still selected. The latter of the two // will not be selected by this algorithm. var minutes = new double[requestCount]; // Perform one check for each possible vlog request, // since users can have more than one request per day. for (uint i = 1; i <= Math.Min(_options.MaxDailyVlogRequestLimit, user.DailyVlogRequestLimit); i++) { // Get the matching minute on which a user should receive // a request and correct it using the users timezone. var userMinute = GetHashMinute(user, day, i); var userMinuteCorrected = userMinute - user.TimeZone.BaseUtcOffset.TotalMinutes; if (userMinuteCorrected < 0) { userMinuteCorrected += 60 * 24; } minutes[i - 1] = userMinuteCorrected; } for (int i = 0; i < requestCount; i++) { // If any of our selected minutes matches the current one, continue with it. // Compare it to the other minutes to ensure a minimum interval between them. if (minutes[i] == thisMinute) { var withinMinimumInterval = false; for (int j = 0; j < requestCount; j++) { var delta = minutes[i] - minutes[j]; if (j != i && delta < interval && delta >= 0) { withinMinimumInterval = true; } } // Only return the user if none of the other minutes were // within (before) the interval of the currently selected minute. if (!withinMinimumInterval) { yield return(user); } } } } }
internal static string DateToString(DateTimeOffset dateTime) { return dateTime.ToUniversalTime().ToString("r", CultureInfo.InvariantCulture); }
public override void SetNextFireTimeUtc(DateTimeOffset?nextFireTime) { _manualNextTime = nextFireTime?.ToUniversalTime(); }
public void TimestampTz() { var tzOffset = TimeZoneInfo.Local.BaseUtcOffset; if (tzOffset == TimeSpan.Zero) TestUtil.Inconclusive("Test cannot run when machine timezone is UTC"); var dateTimeUtc = new DateTime(2015, 1, 27, 8, 45, 12, 345, DateTimeKind.Utc); var dateTimeLocal = dateTimeUtc.ToLocalTime(); var dateTimeUnspecified = new DateTime(dateTimeUtc.Ticks, DateTimeKind.Unspecified); var nDateTimeUtc = new NpgsqlDateTime(dateTimeUtc); var nDateTimeLocal = nDateTimeUtc.ToLocalTime(); var nDateTimeUnspecified = new NpgsqlDateTime(nDateTimeUtc.Ticks, DateTimeKind.Unspecified); var dateTimeOffset = new DateTimeOffset(dateTimeLocal, tzOffset); using (var cmd = new NpgsqlCommand("SELECT @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9", Conn)) { cmd.Parameters.AddWithValue("p1", NpgsqlDbType.TimestampTZ, dateTimeUtc); cmd.Parameters.AddWithValue("p2", NpgsqlDbType.TimestampTZ, dateTimeLocal); cmd.Parameters.AddWithValue("p3", NpgsqlDbType.TimestampTZ, dateTimeUnspecified); cmd.Parameters.AddWithValue("p4", NpgsqlDbType.TimestampTZ, nDateTimeUtc); cmd.Parameters.AddWithValue("p5", NpgsqlDbType.TimestampTZ, nDateTimeLocal); cmd.Parameters.AddWithValue("p6", NpgsqlDbType.TimestampTZ, nDateTimeUnspecified); cmd.Parameters.AddWithValue("p7", dateTimeUtc); cmd.Parameters.AddWithValue("p8", nDateTimeUtc); cmd.Parameters.AddWithValue("p9", dateTimeOffset); using (var reader = cmd.ExecuteReader()) { reader.Read(); for (var i = 0; i < cmd.Parameters.Count; i++) { // Regular type (DateTime) Assert.That(reader.GetFieldType(i), Is.EqualTo(typeof(DateTime))); Assert.That(reader.GetDateTime(i), Is.EqualTo(dateTimeUtc)); Assert.That(reader.GetFieldValue<DateTime>(i).Kind, Is.EqualTo(DateTimeKind.Utc)); Assert.That(reader[i], Is.EqualTo(dateTimeUtc)); Assert.That(reader.GetValue(i), Is.EqualTo(dateTimeUtc)); // Provider-specific type (NpgsqlDateTime) Assert.That(reader.GetTimeStamp(i), Is.EqualTo(nDateTimeUtc)); Assert.That(reader.GetProviderSpecificFieldType(i), Is.EqualTo(typeof(NpgsqlDateTime))); Assert.That(reader.GetProviderSpecificValue(i), Is.EqualTo(nDateTimeUtc)); Assert.That(reader.GetFieldValue<NpgsqlDateTime>(i), Is.EqualTo(nDateTimeUtc)); // DateTimeOffset Assert.That(reader.GetFieldValue<DateTimeOffset>(i), Is.EqualTo(dateTimeOffset.ToUniversalTime())); } } } }
public override void SetPreviousFireTimeUtc(DateTimeOffset?previousFireTime) { _lastFireTime = previousFireTime?.ToUniversalTime(); }
private static void AssertApproximatelyEqual(DateTimeOffset actual, DateTimeOffset expected) { Assert.InRange( actual.ToUniversalTime() - expected.ToUniversalTime(), TimeSpan.FromSeconds(-1), TimeSpan.FromSeconds(1)); }
public static int ToEpoch(this DateTimeOffset fromDate) { var utc = (fromDate.ToUniversalTime().Ticks - EPOCH_TICKS) / TimeSpan.TicksPerSecond; return(Convert.ToInt32(utc)); }