public string FormatStartDate(DateTimeOffset startDateTime)
 {
     var timeOfDay = startDateTime.TimeOfDay;
     return timeOfDay.Hours == 0
                 ? startDateTime.ToString(DateOnlyPattern)
                 : startDateTime.ToString(DateAndTimePattern);
 }
        /// <summary>
        /// 定义将时间点对象 <see cref="System.DateTimeOffset"/> 转换为字符串的方法。
        /// </summary>
        /// <param name="datetimeOffset"></param>
        /// <returns></returns>
        protected override string ToString(DateTimeOffset datetimeOffset)
        {
            if (datetimeOffset.HasDate())
                return datetimeOffset.HasTime() ? base.ToString(datetimeOffset) : datetimeOffset.ToString(this.Culture.DateTimeFormat.ShortDatePattern, this.Culture);
            else if (datetimeOffset.HasTime())
                return datetimeOffset.ToString(this.Culture.DateTimeFormat.ShortTimePattern, this.Culture);

            return base.ToString(datetimeOffset);
        }
Example #3
0
 public HistoryEntry(string id, DateTimeOffset timestamp, string operatorName, string alarmStatus, string alarmState, string response)
 {
     Id = id;
     Timestamp = timestamp.ToString("G", CultureInfo.CurrentCulture);
     SortableTimestamp = timestamp.ToString("s", CultureInfo.InvariantCulture);
     OperatorName = operatorName;
     AlarmStatus = alarmStatus;
     AlarmState = alarmState;
     Response = response;
 }
Example #4
0
 /// <summary>
 /// Creates an immutable message object
 /// </summary>
 /// <param name="id">Message id</param>
 /// <param name="description">Message description</param>
 /// <param name="partitionId">The GUID of the partition the message occurred on</param>
 /// <param name="partitionName">The name of the partition the message occurred on</param>
 /// <param name="isPublic">True if the message is public, otherwise false</param>
 /// <param name="messageDateTime">The Date and Time the message occurred.</param>
 public Message(Guid id, string description, Guid partitionId, string partitionName, bool isPublic, DateTimeOffset messageDateTime)
 {
     Id = id;
     Description = description;
     PartitionId = partitionId;
     PartitionName = partitionName;
     IsPublic = isPublic;
     MessageDateTime = messageDateTime;
     MessageDateString = MessageDateTime.ToString("d", CultureInfo.CurrentCulture);
     MessageTimeString = MessageDateTime.ToString("t", CultureInfo.CurrentCulture);
     MessageDateTimeString = MessageDateTime.ToString("G", CultureInfo.CurrentCulture);
     MessageDateTimeSortableString = MessageDateTime.ToString("s", CultureInfo.InvariantCulture);
     MessageUtcDateTime = (long) (MessageDateTime.UtcDateTime - new DateTime(1970,1,1,0,0,0,0,DateTimeKind.Utc)).TotalMilliseconds;
 }
Example #5
0
 /// <summary>
 /// Creates an immutable Case object
 /// </summary>        
 /// <param name="id">Globally unique identifier for the case</param>
 /// <param name="title">Title of the case</param>
 /// <param name="createdBy">User who created the case</param>
 /// <param name="createdDateTime">Time and Date that the case was created</param>
 /// <param name="owner">User who owns the case</param>
 /// <param name="notes">The list of notes on the case</param>
 /// <param name="status">Status of the case</param>
 public Case(string id, string title, string createdBy, DateTimeOffset createdDateTime, string owner, IEnumerable<CaseNote> notes, CaseStatus status)
 {
     Id = id;
     Title = title;
     CreatedBy = createdBy;
     CreatedDateTime = createdDateTime;
     CreatedDateString = CreatedDateTime.ToString("d", CultureInfo.CurrentCulture);
     CreatedTimeString = CreatedDateTime.ToString("t", CultureInfo.CurrentCulture);
     CreatedDateTimeString = CreatedDateTime.ToString("g", CultureInfo.CurrentCulture);
     CreatedDateTimeSortableString = CreatedDateTime.ToString("s", CultureInfo.InvariantCulture);
     Owner = owner;
     Notes = notes.ToList();
     StatusEnum = status;
 }
Example #6
0
        /// <summary>
        ///   Determines if the time is in the specified time period.
        /// </summary>
        /// <param name="now">
        ///   The time to compare.
        /// </param>
        /// <param name="inclusiveStart">The inclusive start time.</param>
        /// <param name="exclusiveEnd">The exclusive end time.</param>
        /// <returns>
        ///   <b>true</b> if <paramref name="now"/> within the specified period; otherwise <b>false</b>.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">
        ///   <paramref name="exclusiveEnd"/> must be greater than <paramref name="inclusiveStart"/>.
        /// </exception>
        /// <example>
        ///   <code title="Credit Card Check" source="SepiaExamples\TimeExample.cs" region="Credit Card Check" language="C#" />
        /// </example>
        public static bool Between(this DateTimeOffset now, DateTimeOffset inclusiveStart, DateTimeOffset exclusiveEnd)
        {
            if (exclusiveEnd <= inclusiveStart)
                throw new ArgumentOutOfRangeException("end", exclusiveEnd.ToString("o"), string.Format("The end must be greater than the start '{0:o}'.", inclusiveStart));

            return inclusiveStart <= now && now < exclusiveEnd;
        }
        internal void ProcessRequest(ResourceSession rpResourceSession, Session rpSession)
        {
            if (CurrentMode == CacheMode.Disabled)
                return;

            string rFilename;
            var rNoVerification = CheckFileInCache(rpResourceSession.Path, out rFilename);

            rpResourceSession.CacheFilename = rFilename;

            if (rNoVerification == null)
                return;

            if (!rNoVerification.Value)
            {
                var rTimestamp = new DateTimeOffset(File.GetLastWriteTime(rFilename));

                if (rpResourceSession.Path.OICContains("mainD2.swf") || rpResourceSession.Path.OICContains(".js") || !CheckFileVersionAndTimestamp(rpResourceSession, rTimestamp))
                {
                    rpSession.oRequest["If-Modified-Since"] = rTimestamp.ToString("R");
                    rpSession.bBufferResponse = true;

                    return;
                }
            }

            rpSession.utilCreateResponseAndBypassServer();
            LoadFile(rFilename, rpResourceSession, rpSession);
        }
        public void SerializationTests_DateTimeOffset()
        {
            // Local Kind
            DateTime inputLocalDateTime = DateTime.Now;
            DateTimeOffset inputLocal = new DateTimeOffset(inputLocalDateTime);

            DateTimeOffset outputLocal = SerializationManager.RoundTripSerializationForTesting(inputLocal);
            Assert.AreEqual(inputLocal, outputLocal, "Local time");
            Assert.AreEqual(
                inputLocal.ToString(CultureInfo.InvariantCulture),
                outputLocal.ToString(CultureInfo.InvariantCulture));
            Assert.AreEqual(inputLocal.DateTime.Kind, outputLocal.DateTime.Kind);

            // UTC Kind
            DateTime inputUtcDateTime = DateTime.UtcNow;
            DateTimeOffset inputUtc = new DateTimeOffset(inputUtcDateTime);

            DateTimeOffset outputUtc = SerializationManager.RoundTripSerializationForTesting(inputUtc);
            Assert.AreEqual(inputUtc, outputUtc, "UTC time");
            Assert.AreEqual(
                inputUtc.ToString(CultureInfo.InvariantCulture),
                outputUtc.ToString(CultureInfo.InvariantCulture));
            Assert.AreEqual(inputUtc.DateTime.Kind, outputUtc.DateTime.Kind);

            // Unspecified Kind
            DateTime inputUnspecifiedDateTime = new DateTime(0x08d27e2c0cc7dfb9);
            DateTimeOffset inputUnspecified = new DateTimeOffset(inputUnspecifiedDateTime);

            DateTimeOffset outputUnspecified = SerializationManager.RoundTripSerializationForTesting(inputUnspecified);
            Assert.AreEqual(inputUnspecified, outputUnspecified, "Unspecified time");
            Assert.AreEqual(
                inputUnspecified.ToString(CultureInfo.InvariantCulture),
                outputUnspecified.ToString(CultureInfo.InvariantCulture));
            Assert.AreEqual(inputUnspecified.DateTime.Kind, outputUnspecified.DateTime.Kind);
        }
        public void DateTimeOffsetScenarioShouldFail()
        {
            var date = new DateTimeOffset(new DateTime(2000, 6, 1), TimeSpan.Zero);
            var dateString = date.ToString();
            var exptected = new DateTimeOffset(new DateTime(2000, 6, 1, 1, 0, 1), TimeSpan.Zero);
            var expectedDate = exptected.ToString();
            Verify.ShouldFail(() =>
date.ShouldBe(exptected, TimeSpan.FromHours(1), "Some additional context"),

errorWithSource:
[email protected]"date
    should be within
01:00:00
    of
{expectedDate}
    but was
{dateString}

Additional Info:
    Some additional context",

errorWithoutSource:
[email protected]"{dateString}
    should be within
01:00:00
    of
{expectedDate}
    but was not

Additional Info:
    Some additional context");
        }
Example #10
0
 public RepositoryInfo(Repository repository, DateTimeOffset commitDate, string hash)
 {
     ProjectName = repository.Name;
     ProjectId = repository.Id;
     Date = commitDate.ToString("yyyy-MM-dd");
     Hash = hash;
 }
Example #11
0
 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);
 }
 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);
 }
        private string PrintNetworkUsage(NetworkUsage networkUsage, DateTimeOffset startTime)
        {
            string result = "Usage from " + startTime.ToString() + " to " + (startTime + networkUsage.ConnectionDuration).ToString() +
                "\n\tBytes sent: " + networkUsage.BytesSent +
                "\n\tBytes received: " + networkUsage.BytesReceived + "\n";

            return result;
        }
        public static void ConvertTo_WithContext()
        {
            DateTimeFormatInfo formatInfo = (DateTimeFormatInfo)CultureInfo.CurrentCulture.GetFormat(typeof(DateTimeFormatInfo));
            string formatWithTime = formatInfo.ShortDatePattern + " " + formatInfo.ShortTimePattern + " zzz";
            string format = formatInfo.ShortDatePattern + " zzz";
            DateTimeOffset testDateAndTime = new DateTimeOffset(new DateTime(1998, 12, 5, 22, 30, 30));

            ConvertTo_WithContext(new object[5, 3]
                {
                    { DateTimeOffsetConverterTests.s_testOffset, DateTimeOffsetConverterTests.s_testOffset.ToString(format, CultureInfo.CurrentCulture), null },
                    { testDateAndTime, testDateAndTime.ToString(formatWithTime, CultureInfo.CurrentCulture), null },
                    { DateTimeOffset.MinValue, string.Empty, null },
                    { DateTimeOffsetConverterTests.s_testOffset, DateTimeOffsetConverterTests.s_testOffset.ToString("yyyy-MM-dd zzz", CultureInfo.InvariantCulture), CultureInfo.InvariantCulture },
                    { testDateAndTime, testDateAndTime.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture }
                },
                DateTimeOffsetConverterTests.s_converter);
        }
        private string PrintNetworkUsage(AttributedNetworkUsage networkUsage, DateTimeOffset startTime, DateTimeOffset endTime)
        {
            string result = "Usage by " + networkUsage.AttributionName +
                "\n\tFrom: " + startTime.ToString() + " to " + endTime.ToString() +
                "\n\tBytes sent: " + networkUsage.BytesSent +
                "\n\tBytes received: " + networkUsage.BytesReceived + "\n";

            return result;
        }
        public void SetVersion(DateTimeOffset version, IDictionary<string, string> metadata)
        {
            if (metadata == null)
            {
                throw new ArgumentNullException("metadata");
            }

            metadata[VersionMetadataKey] = version.ToString("o", CultureInfo.InvariantCulture);
        }
        /// <summary>
        /// Wandelt eine Zeitangabe im DateTimeOffset Format um in einen String, um sie in einer
        /// SQLite Datenbank zu speichern.
        /// </summary>
        /// <param name="datetime">Das umzuwandelnde Datum mit zugehöriger Uhrzeit und Zeitzonenoffset.</param>
        /// <returns>Das Ergebnis der Umwandlung als String.</returns>
        public static string DateTimeToSQLite(DateTimeOffset datetime)
        {
            string dateTimeFormat = string.Empty;
            
            dateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffzzzz";
            CultureInfo cultureInfo = new CultureInfo("de-DE");
            string datetimeString = datetime.ToString(dateTimeFormat, cultureInfo);

            return datetimeString;
        }
Example #18
0
 public async Task SetCurrentTimeAsync(DateTimeOffset UtcTime, int OffsetInMinute)
 {
     var req = new TimeOffset
     {
         DateTime = UtcTime.ToString("yyyy-MM-ddTHH:mm:ssZ"),
         TimeZoneOffsetMinute = OffsetInMinute,
         DstOffsetMinute = 0
     };
     await NoValue(RequestGenerator.Serialize("setCurrentTime", ApiVersion.V1_0, req)).ConfigureAwait(false); ;
 }
 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();
 }
        private String BuildCalendarUri(DateTimeOffset startDate, DateTimeOffset endDate)
        {
            string start = startDate.ToString("O");
            string end = endDate.ToString("O");

            string uri = string.Format("calendarview?startDateTime={0}&endDateTime={1}", start, end);
            uri += "&$orderby=start/dateTime";

            return uri;
        }
        private string BuildCalendarUri(DateTimeOffset startDate, DateTimeOffset endDate)
        {
            string start = startDate.ToString("O");
            string end = endDate.ToString("O");

            string uri = $"calendarview?startDateTime={start}&endDateTime={end}";
            uri += "&$orderby=start/dateTime";

            return uri;
        }
Example #22
0
        private string GetTimestampString(DateTime? timestamp)
        {
            if (timestamp.HasValue)
            {
                DateTime local =
                    new DateTimeOffset(timestamp.Value).ToLocalTime().DateTime;
                return local.ToString("g");
            }

            return string.Empty;
        }
Example #23
0
        public string GetDateNthFormat(DateTimeOffset dateTimeOffset)
        {
            var ending = string.Empty;

            if (dateTimeOffset.Day.ToString().EndsWith("1"))
            {
                ending = dateTimeOffset.Day.ToString().StartsWith("1") && dateTimeOffset.Day != 1 ? "th" : "st";
            }
            else if (dateTimeOffset.Day.ToString().EndsWith("2"))
            {
                ending = dateTimeOffset.Day.ToString().StartsWith("1") ? "th" : "nd";
            }
            else if (dateTimeOffset.Day.ToString().EndsWith("3"))
            {
                ending = dateTimeOffset.Day.ToString().StartsWith("1") ? "th" : "rd";
            }
            else
                ending = "th";
            return string.Format("{0} {1}{2}", dateTimeOffset.ToString("MMM", System.Globalization.DateTimeFormatInfo.InvariantInfo), dateTimeOffset.ToString("dd"), ending);
        }
Example #24
0
 static string TryFormat(DateTimeOffset dateTime, string format)
 {
     try
     {
         return dateTime.ToString(format);
     }
     catch (FormatException)
     {
         return null;
     }
 }
Example #25
0
        public static string GetBugFixedDateTimeOffset(Expression expression)
        {
            string dateTimePartStr = StripCurleyBraces(expression.DataMembers.Item(2).Value);
            string offsetPartStr = StripCurleyBraces(expression.DataMembers.Item(11).Value);

            TimeSpan offset = TimeSpan.Parse(offsetPartStr);
            DateTime dateTime = DateTime.Parse(dateTimePartStr);

            DateTimeOffset dateTimeOffset = new DateTimeOffset(dateTime, offset);

            return dateTimeOffset.ToString();
        }
Example #26
0
        /// <summary>
        /// Creates an immutable Alarm object
        /// </summary>
        /// <param name="id">Event id</param>
        /// <param name="description">Description of the Alarm</param>
        /// <param name="partitionId">The Id of the partition the event occurred on</param>
        /// <param name="partitionName">The name of the partition the event occurred on</param>
        /// <param name="isPublic">True if the event is public, otherwise false</param>
        /// <param name="messageDateTime">The Date and Time the alarm occurred.</param>
        /// <param name="alarmTypeDescription">The name of the alarm type</param>
        /// <param name="category">The category of the alarm</param>
        /// <param name="priority">The alarms priority</param>
        /// <param name="isResponseRequired">True if the alarm requires a response, otherwise false</param>
        /// <param name="isAcknowledgeRequired">True if the alarm requires acknowledgement, otherwise false</param>
        /// <param name="alarmState">The ID of the AlarmState or condition</param>
        /// <param name="alarmStateDescription">The name of the AlarmState or condition</param>
        /// <param name="stateDateTime">The timestamp of the last time the AlarmState change</param>
        /// <param name="conditionSequence">incremented every time the triggering item changes state</param>
        /// <param name="site">The site object from which the alarm was generated.</param>
        /// <param name="sourceState">The ID of the source state.</param>
        /// <param name="sourceStateDescription">The source state description.</param>
        /// <param name="escalation">The escalation level of the alarm.</param>
        /// <param name="instructions">The instructions given with this alarm.</param>
        /// <param name="isPublicDescription">The text description for the IsPublic field.</param>
        /// <param name="isPending">True if the Alarm is in a Pending state, otherwise false</param>
        /// <param name="isCompletable">True if the Alarm can be Completed, otherwise false</param>
        /// <param name="isRespondable">True if one can Respond to the Alarm, otherwise false</param>
        /// <param name="isRemovable">True if the Alarm can be Removed, otherwise false</param>
        /// <param name="isCompleted">True if the Alarm can be completed, otherwise false</param>
        public Alarm(Guid id, string description, Guid partitionId, string partitionName, bool isPublic, DateTimeOffset messageDateTime,
            string alarmTypeDescription, string category, int priority, bool isResponseRequired, bool isAcknowledgeRequired,
            int alarmState, string alarmStateDescription, DateTimeOffset stateDateTime, int conditionSequence, string site,
            int sourceState, string sourceStateDescription, int escalation, string instructions, string isPublicDescription,
            bool isPending,
            bool isCompletable,
            bool isRespondable,
            bool isRemovable,
            bool isCompleted
            )
            : base(id, description, partitionId, partitionName, isPublic, messageDateTime)
        {
            AlarmState = alarmState;
            AlarmStateDescription = alarmStateDescription;
            StateDateTime = stateDateTime;
            StateDateString = StateDateTime.ToString("d", CultureInfo.CurrentCulture);
            StateTimeString = StateDateTime.ToString("t", CultureInfo.CurrentCulture);
            StateDateTimeString = StateDateTime.ToString("G", CultureInfo.CurrentCulture);
            StateDateTimeSortableString = StateDateTime.ToString("s", CultureInfo.InvariantCulture);
            ConditionSequence = conditionSequence;

            IsAcknowledgeRequired = isAcknowledgeRequired;
            IsResponseRequired = isResponseRequired;
            Priority = priority;
            Category = category;
            AlarmTypeDescription = alarmTypeDescription;
            SourceState = sourceState;
            SourceStateDescription = sourceStateDescription;
            Site = site;
            Escalation = escalation;
            Instructions = instructions;
            IsPublicDescription = isPublicDescription;

            IsPending = isPending;
            IsCompletable = isCompletable;
            IsRespondable = isRespondable;
            IsRemovable = isRemovable;
            IsCompleted = isCompleted;
        }
        public ReportControllerTests()
        {
            TestCallsigns = new List<string>(Fixture.CreateMany<string>());
            TestCallsign = TestCallsigns.First();
            TestReadingsSet1 = new List<LocationRecord>(Fixture.CreateMany<LocationRecord>());
            TestReadingsSet2 = new List<LocationRecord>(Fixture.CreateMany<LocationRecord>());
            TestDate = Fixture.Create<DateTimeOffset>().Date;
            TestDateString = TestDate.ToString("yyyyMMdd");
            BadDate = Fixture.Create<string>();

            TestLogEntries = new List<LogEntry>(Fixture.Build<LogEntry>().With(p => p.Type, LogEventType.UserLogIn).Without(l => l.Properties).CreateMany());
            TestLogEntries.AddRange(Fixture.Build<LogEntry>().With(p => p.Type, LogEventType.UnknownEvent).Without(l => l.Properties).With(l => l.Date, DateTimeOffset.Now.Date).CreateMany());
        }
        public void Visit_DateTimeOffset_constant_expression_generates_correct_key()
        {
            var dateTime = DateTime.Now;
            var dateTimeOffset = new DateTimeOffset(dateTime);

            var keyGen = new ExpressionKeyGen();
            keyGen.Visit(DbExpressionBuilder.Constant(dateTimeOffset));

            var expectedKey = dateTimeOffset.ToString("o")
                + ":Edm.DateTimeOffset(Nullable=True,DefaultValue=,Precision=)";

            Assert.Equal(expectedKey, keyGen.Key);
        }
 /// <summary>
 /// Gets the parameters.
 /// </summary>
 /// <param name="jobName">Name of the job.</param>
 /// <param name="scheduledTime">The scheduled time.</param>
 /// <returns></returns>
 private object GetParameters(string jobName,
     DateTimeOffset scheduledTime)
 {
     return new
     {
         JobJey = (RedisKey) RedisNames.JobNames,
         JobName = jobName,
         StatusKey = (RedisKey) RedisNames.Status,
         JobEventKey = (RedisKey) RedisNames.JobEvent,
         JobNameScheduled = string.Concat(jobName, "|scheduled"),
         ScheduledTime = scheduledTime.ToString(System.Globalization.CultureInfo.InvariantCulture)
     };
 }
        /// <summary>
        /// Gets the currently featured map, if any.
        /// </summary>
        /// <param name="table">The Azure table to use.</param>
        /// <param name="featuredDate">The featured date to use.</param>
        /// <returns>Returns the currently featured map.</returns>
        public static async Task<MapEntity> GetFeaturedMap(this AzureTable<MapEntity> table, DateTimeOffset featuredDate)
        {
            Guard.NotNull(() => table);
            Guard.NotNull(() => featuredDate);

            TableQuery<MapEntity> query = new TableQuery<MapEntity>().Where(
                TableQuery.CombineFilters(
                    TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, MapEntity.FeaturedKey),
                    TableOperators.And,
                    TableQuery.GenerateFilterCondition("FeaturedDate", QueryComparisons.Equal, featuredDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))));

            return (await table.GetFromQuery(query)).FirstOrDefault();
        }