• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# DateTimeOffset类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中DateTimeOffset的典型用法代码示例。如果您正苦于以下问题:C# DateTimeOffset类的具体用法?C# DateTimeOffset怎么用?C# DateTimeOffset使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



DateTimeOffset类属于命名空间,在下文中一共展示了DateTimeOffset类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: GetNextIncludedTimeUtc

        /// <summary>
        /// Determine the next time (in milliseconds) that is 'included' by the
        /// Calendar after the given time. Return the original value if timeStamp is
        /// included. Return DateTime.MinValue if all days are excluded.
        /// <para>
        /// Note that this Calendar is only has full-day precision.
        /// </para>
        /// </summary>
        /// <param name="timeUtc"></param>
        /// <returns></returns>
        public override DateTimeOffset GetNextIncludedTimeUtc(DateTimeOffset timeUtc)
        {
            if (base.AreAllDaysExcluded())
            {
                return DateTime.MinValue;
            }

            // Call base calendar implementation first
            DateTimeOffset baseTime = base.GetNextIncludedTimeUtc(timeUtc);
            if ((baseTime != DateTimeOffset.MinValue) && (baseTime > timeUtc))
            {
                timeUtc = baseTime;
            }

            // Get timestamp for 00:00:00
            //DateTime d = timeUtc.Date;   --commented out for local time impl
            DateTime d = timeUtc.ToLocalTime().Date;

            if (!IsDayExcluded(d.DayOfWeek))
            {
                return timeUtc;
            } // return the original value

            while (IsDayExcluded(d.DayOfWeek))
            {
                d = d.AddDays(1);
            }

            return d;
        }
开发者ID:bobbyfox,项目名称:AndrewSmith.Quartz.TextToSchedule,代码行数:40,代码来源:LocalWeeklyCalendar.cs


示例2: OnClosing

		// not virtual as is called from the ctor
		protected void OnClosing(DateTimeOffset closed)
		{
			DomainEventHandler<IssueClosed> handler = Closing;
			if (handler != null) handler(this, new DomainEventEventArgs<IssueClosed>(
				new IssueClosed(Id) {  Closed = closed },
				doClose));
		}
开发者ID:dgg,项目名称:Dgg.Cqrs.Sample,代码行数:8,代码来源:ClosedIssue.cs


示例3: IndexDecider_EndsUpInTheOutput

        public void IndexDecider_EndsUpInTheOutput()
        {
            //DO NOTE that you cant send objects as scalar values through Logger.*("{Scalar}", {});
            var timestamp = new DateTimeOffset(2013, 05, 28, 22, 10, 20, 666, TimeSpan.FromHours(10));
            const string messageTemplate = "{Song}++ @{Complex}";
            var template = new MessageTemplateParser().Parse(messageTemplate);
            _options.IndexDecider = (l, utcTime) => string.Format("logstash-{1}-{0:yyyy.MM.dd}", utcTime, l.Level.ToString().ToLowerInvariant());
            using (var sink = new ElasticsearchSink(_options))
            {
                var properties = new List<LogEventProperty> { new LogEventProperty("Song", new ScalarValue("New Macabre")) };
                var e = new LogEvent(timestamp, LogEventLevel.Information, null, template, properties);
                sink.Emit(e);
                var exception = new ArgumentException("parameter");
                properties = new List<LogEventProperty>
                {
                    new LogEventProperty("Song", new ScalarValue("Old Macabre")),
                    new LogEventProperty("Complex", new ScalarValue(new { A  = 1, B = 2}))
                };
                e = new LogEvent(timestamp.AddYears(-2), LogEventLevel.Fatal, exception, template, properties);
                sink.Emit(e);
            }

            _seenHttpPosts.Should().NotBeEmpty().And.HaveCount(1);
            var json = _seenHttpPosts.First();
            var bulkJsonPieces = json.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
            bulkJsonPieces.Should().HaveCount(4);
            bulkJsonPieces[0].Should().Contain(@"""_index"":""logstash-information-2013.05.28");
            bulkJsonPieces[1].Should().Contain("New Macabre");
            bulkJsonPieces[2].Should().Contain(@"""_index"":""logstash-fatal-2011.05.28");
            bulkJsonPieces[3].Should().Contain("Old Macabre");

            //serilog by default simpy .ToString()'s unknown objects
            bulkJsonPieces[3].Should().Contain("Complex\":\"{");

        }
开发者ID:leachdaniel,项目名称:serilog-sinks-elasticsearch,代码行数:35,代码来源:IndexDeciderTests.cs


示例4: ChainedHeader

 public ChainedHeader(BlockHeader blockHeader, int height, BigInteger totalWork, DateTimeOffset dateSeen)
 {
     BlockHeader = blockHeader;
     Height = height;
     TotalWork = totalWork;
     DateSeen = dateSeen;
 }
开发者ID:pmlyon,项目名称:BitSharp,代码行数:7,代码来源:ChainedHeader.cs


示例5: UsesCustomPropertyNames

 public async Task UsesCustomPropertyNames()
 {
     try
     {
         await new HttpClient().GetStringAsync("http://i.do.not.exist");
     }
     catch (Exception e)
     {
         var timestamp = new DateTimeOffset(2013, 05, 28, 22, 10, 20, 666, TimeSpan.FromHours(10));
         var messageTemplate = "{Song}++";
         var template = new MessageTemplateParser().Parse(messageTemplate);
         using (var sink = new ElasticsearchSink(_options))
         {
             var properties = new List<LogEventProperty>
             {
                 new LogEventProperty("Song", new ScalarValue("New Macabre")), 
                 new LogEventProperty("Complex", new ScalarValue(new { A = 1, B = 2 }))
             };
             var logEvent = new LogEvent(timestamp, LogEventLevel.Information, e, template, properties);
             sink.Emit(logEvent);
             logEvent = new LogEvent(timestamp.AddDays(2), LogEventLevel.Information, e, template, properties);
             sink.Emit(logEvent);
         }
         _seenHttpPosts.Should().NotBeEmpty().And.HaveCount(1);
         var json = _seenHttpPosts.First();
         var bulkJsonPieces = json.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
         bulkJsonPieces.Should().HaveCount(4);
         bulkJsonPieces[0].Should().Contain(@"""_index"":""logstash-2013.05.28");
         bulkJsonPieces[1].Should().Contain("New Macabre");
         bulkJsonPieces[1].Should().NotContain("Properties\"");
         bulkJsonPieces[1].Should().Contain("fields\":{");
         bulkJsonPieces[1].Should().Contain("@timestamp");
         bulkJsonPieces[2].Should().Contain(@"""_index"":""logstash-2013.05.30");
     }
 }
开发者ID:alexvaluyskiy,项目名称:serilog-sinks-elasticsearch,代码行数:35,代码来源:PropertyNameTests.cs


示例6: GetBuildDescription

        internal static string GetBuildDescription(Build build, bool includeRefDescription, DateTimeOffset now)
        {
            if (build == null) throw new ArgumentNullException("build");

            var @ref = "";
            if (includeRefDescription)
                @ref = String.Concat(" on ", GetRefDescription(build));

            if (!build.Started.HasValue)
            {
                if (!build.Queued.HasValue)
                    return String.Format("Build #{0}{1} queued.", build.Id, @ref);

                return String.Format("Build #{0}{1} queued {2} seconds ago.", build.Id, @ref, build.Queued.Value.Since(now));
            }

            if (!build.Finished.HasValue)
                return String.Format("Build #{0}{1} started {2} seconds ago.", build.Id, @ref, build.Started.Value.Since(now));

            if (!build.Succeeded.HasValue)
                return String.Format("Build #{0}{1} finished in {2} seconds.", build.Id, @ref, build.Started.Value.Until(build.Finished.Value));

            if (build.Succeeded.Value)
                return String.Format("Build #{0}{1} succeeded in {2} seconds.", build.Id, @ref, build.Started.Value.Until(build.Finished.Value));

            return String.Format("Build #{0}{1} failed in {2} seconds.", build.Id, @ref, build.Started.Value.Until(build.Finished.Value));
        }
开发者ID:half-ogre,项目名称:qed,代码行数:27,代码来源:GetBuildDescription.cs


示例7: Syncronize

		private void Syncronize()
		{
			lock (_stopwatch) {
				_baseTime = DateTimeOffset.UtcNow;
				_stopwatch.Restart();
			}
		}
开发者ID:achinn,项目名称:fluentcassandra,代码行数:7,代码来源:DateTimePrecise.cs


示例8: GetHeartbeatMeasurementFromData

        public static HeartbeatMeasurement GetHeartbeatMeasurementFromData(byte[] data, DateTimeOffset timeStamp)
        {
            // Heart Rate profile defined flag values
            const byte HEART_RATE_VALUE_FORMAT = 0x01;
            byte flags = data[0];

            ushort HeartbeatMeasurementValue = 0;

            if (((flags & HEART_RATE_VALUE_FORMAT) != 0))
            {
                HeartbeatMeasurementValue = (ushort)((data[2] << 8) + data[1]);
            }
            else
            {
                HeartbeatMeasurementValue = data[1];
            }

            DateTimeOffset tmpVal = timeStamp;
            if (tmpVal == null)
            {
                tmpVal = DateTimeOffset.Now;
            }
            return new HeartbeatMeasurement
            {
                HeartbeatValue = HeartbeatMeasurementValue,
                Timestamp = tmpVal
            };
        }
开发者ID:DrJukka,项目名称:Heart-rate-monitor-UWP-,代码行数:28,代码来源:HeartbeatMeasurement.cs


示例9: when_getting_now_as_datetimeoffset_should_return_the_mock_provider_now_as_datetimeoffset

        public void when_getting_now_as_datetimeoffset_should_return_the_mock_provider_now_as_datetimeoffset()
        {
            var expectedDate = new DateTimeOffset(20.July(2015));
            _mockProvider.NowAsDateTimeOffset.Returns(expectedDate);

            TimeProvider.Current.NowAsDateTimeOffset.Should().Be(expectedDate);
        }
开发者ID:al-main,项目名称:James.Testing,代码行数:7,代码来源:TimeProviderTests.cs


示例10: IssueCommentItemViewModel

 internal IssueCommentItemViewModel(string body, string login, string avatar, DateTimeOffset createdAt)
 {
     Comment = body;
     Actor = login;
     AvatarUrl = new GitHubAvatar(avatar);
     CreatedAt = createdAt;
 }
开发者ID:zdd910,项目名称:CodeHub,代码行数:7,代码来源:IssueEventItemViewModel.cs


示例11: AbsoluteTimerWaitHandle

        public AbsoluteTimerWaitHandle(DateTimeOffset dueTime)
        {
            _dueTime = dueTime;
            _eventWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);

            SafeWaitHandle = _eventWaitHandle.SafeWaitHandle;

            var dueSpan = (_dueTime - DateTimeOffset.Now);
            var period = new TimeSpan(dueSpan.Ticks / 10);

            if (dueSpan < TimeSpan.Zero)
            {
                _eventWaitHandle.Set();
            }
            else
            {
                _timer = new Timer(period.TotalMilliseconds)
                {
                    AutoReset = false,
                };

                _timer.Elapsed += TimerOnElapsed;

                _timer.Start();
            }
        }
开发者ID:hash,项目名称:trigger.net,代码行数:26,代码来源:PlatformIndependentNative.cs


示例12: Complete

        public override void Complete(
            string completedComments,
            IEnumerable<CreateDocumentParameters> createDocumentParameterObjects,
            IEnumerable<long> documentLibraryIdsToRemove,
            UserForAuditing userForAuditing,
            User user,
            DateTimeOffset completedDate)
        {
            //Addition conditions for completeing a FurtherControlMeasureTask.
            if (TaskStatus == TaskStatus.NoLongerRequired)
            {
                throw new AttemptingToCompleteFurtherControlMeasureTaskThatIsNotRequiredException();
            }

            if (!CanUserComplete(user))
            {
                throw new AttemptingToCompleteFurtherControlMeasureTaskThatTheUserDoesNotHavePermissionToAccess(Id);
            }

            base.Complete(
                completedComments,
                createDocumentParameterObjects,
                documentLibraryIdsToRemove,
                userForAuditing,
                user,
                completedDate);
        }
开发者ID:mnasif786,项目名称:Business-Safe,代码行数:27,代码来源:FurtherControlMeasureTask.cs


示例13: TodayIsTheDayOfThe

 private bool TodayIsTheDayOfThe(DateTime itineraryDate, string eventsTimeZoneId)
 {
     var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(eventsTimeZoneId);
     var utcOffset = timeZoneInfo.GetUtcOffset(itineraryDate);
     var intineraryDateConvertedToEventsTimeZone = new DateTimeOffset(itineraryDate, utcOffset);
     return (intineraryDateConvertedToEventsTimeZone.Date - DateTimeUtcNow().Date).TotalDays == 0;
 }
开发者ID:stevejgordon,项目名称:allReady,代码行数:7,代码来源:SendRequestConfirmationMessagesTheDayOfAnItineraryDate.cs


示例14: LogEntry

 private LogEntry(Object message, IEnumerable<String> categories, DateTimeOffset occurredOn, IDictionary<String, Object> auxiliaryProperties)
 {
     _Message = message;
     _Categories = new ReadOnlyCollection<String>(categories.ToList());
     _OccurredOn = occurredOn;
     _AuxiliaryProperties = new ReadOnlyDictionary<String, Object>(auxiliaryProperties);
 }
开发者ID:PowerDMS,项目名称:NContext,代码行数:7,代码来源:LogEntry.cs


示例15: After

        /// <summary>
        /// Asserts that a <see cref="DateTime"/> occurs a specified amount of time after another <see cref="DateTime"/>.
        /// </summary>
        /// <param name="target">
        /// The <see cref="DateTime"/> to compare the subject with.
        /// </param>
        /// <param name="reason">
        /// A formatted phrase explaining why the assertion should be satisfied. If the phrase does not 
        /// start with the word <i>because</i>, it is prepended to the message.
        /// </param>
        /// <param name="reasonArgs">
        /// Zero or more values to use for filling in any <see cref="string.Format(string,object[])"/> compatible placeholders.
        /// </param>
        public AndConstraint<DateTimeOffsetAssertions> After(DateTimeOffset target, string reason = "", params object[] reasonArgs)
        {
            bool success = Execute.Assertion
                .ForCondition(subject.HasValue)
                .BecauseOf(reason, reasonArgs)
                .FailWith("Expected date and/or time {0} to be " + predicate.DisplayText +
                          " {1} after {2}{reason}, but found a <null> DateTime.",
                    subject, timeSpan, target);

            if (success)
            {
                var actual = subject.Value.Subtract(target);

                if (!predicate.IsMatchedBy(actual, timeSpan))
                {
                    Execute.Assertion
                        .BecauseOf(reason, reasonArgs)
                        .FailWith(
                            "Expected date and/or time {0} to be " + predicate.DisplayText +
                            " {1} after {2}{reason}, but it differs {3}.",
                            subject, timeSpan, target, actual);
                }
            }

            return new AndConstraint<DateTimeOffsetAssertions>(parentAssertions);
        }
开发者ID:nbruce,项目名称:fluentassertions,代码行数:39,代码来源:TimeSpanAssertions.cs


示例16: SubscribeCandles

		/// <summary>
		/// Subscribe to receive new candles.
		/// </summary>
		/// <param name="series">Candles series.</param>
		/// <param name="from">The initial date from which you need to get data.</param>
		/// <param name="to">The final date by which you need to get data.</param>
		public void SubscribeCandles(CandleSeries series, DateTimeOffset from, DateTimeOffset to)
		{
			if (series == null)
				throw new ArgumentNullException("series");

			if (series.CandleType != typeof(TimeFrameCandle))
				throw new ArgumentException(LocalizedStrings.NotSupportCandle.Put("OANDA", series.CandleType), "series");

			if (!(series.Arg is TimeSpan))
				throw new ArgumentException(LocalizedStrings.WrongCandleArg.Put(series.Arg), "series");

			var transactionId = TransactionIdGenerator.GetNextId();

			_series.Add(transactionId, series);

			SendInMessage(new MarketDataMessage
			{
				TransactionId = transactionId,
				DataType = MarketDataTypes.CandleTimeFrame,
				//SecurityId = GetSecurityId(series.Security),
				Arg = series.Arg,
				IsSubscribe = true,
				From = from,
				To = to,
			}.FillSecurityInfo(this, series.Security));
		}
开发者ID:EricGarrison,项目名称:StockSharp,代码行数:32,代码来源:OandaTrader.cs


示例17: GetAsync

 public async Task<ICollection<Appointment>> GetAsync(string userEmail, int year, int month, int day)
 {
     var date = new DateTimeOffset(new DateTime(year, month, day));
     var events = await _office365HttpApi.GetUserDayEvents(userEmail, date);
     var appointments = MapEventsToAppointments(events);
     return appointments;
 }
开发者ID:geekpivot,项目名称:HealthClinic.biz,代码行数:7,代码来源:Office365AppointmentsRepository.cs


示例18: InitCustomers

        private static void InitCustomers()
        {
            DateTimeOffset dto = new DateTimeOffset(2015, 1, 1, 1, 2, 3, 4, TimeSpan.Zero);
            _customers = Enumerable.Range(1, 5).Select(e =>
                new DCustomer
                {
                    Id = e,
                    DateTime = dto.AddYears(e).DateTime,
                    Offset = e % 2 == 0 ? dto.AddMonths(e) : dto.AddDays(e).AddMilliseconds(10),
                    Date = e % 2 == 0 ? dto.AddDays(e).Date : dto.AddDays(-e).Date,
                    TimeOfDay = e % 3 == 0 ? dto.AddHours(e).TimeOfDay : dto.AddHours(-e).AddMilliseconds(10).TimeOfDay,

                    NullableDateTime = e % 2 == 0 ? (DateTime?)null : dto.AddYears(e).DateTime,
                    NullableOffset = e % 3 == 0 ? (DateTimeOffset?)null : dto.AddMonths(e),
                    NullableDate = e % 2 == 0 ? (Date?)null : dto.AddDays(e).Date,
                    NullableTimeOfDay = e % 3 == 0 ? (TimeOfDay?)null : dto.AddHours(e).TimeOfDay,

                    DateTimes = new [] { dto.AddYears(e).DateTime, dto.AddMonths(e).DateTime },
                    Offsets = new [] { dto.AddMonths(e), dto.AddDays(e) },
                    Dates = new [] { (Date)dto.AddYears(e).Date, (Date)dto.AddMonths(e).Date },
                    TimeOfDays = new [] { (TimeOfDay)dto.AddHours(e).TimeOfDay, (TimeOfDay)dto.AddMinutes(e).TimeOfDay },

                    NullableDateTimes = new [] { dto.AddYears(e).DateTime, (DateTime?)null, dto.AddMonths(e).DateTime },
                    NullableOffsets = new [] { dto.AddMonths(e), (DateTimeOffset?)null, dto.AddDays(e) },
                    NullableDates = new [] { (Date)dto.AddYears(e).Date, (Date?)null, (Date)dto.AddMonths(e).Date },
                    NullableTimeOfDays = new [] { (TimeOfDay)dto.AddHours(e).TimeOfDay, (TimeOfDay?)null, (TimeOfDay)dto.AddMinutes(e).TimeOfDay },

                }).ToList();
        }
开发者ID:shailendra9,项目名称:WebApi,代码行数:29,代码来源:DateAndTimeOfDayController.cs


示例19: GetMeetingsFromDatabase

        /// <summary>
        /// Loads a list of meetings for a given date from the database
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        internal static List<Tuple<string, DateTime, int>> GetMeetingsFromDatabase(DateTimeOffset date)
        {
            var meetings = new List<Tuple<string, DateTime, int>>();
            try
            {
                var query = "SELECT subject, time, durationInMins FROM " + Settings.MeetingsTable + " "
                            + "WHERE " + Database.GetInstance().GetDateFilteringStringForQuery(VisType.Day, date) + " "
                            + "AND subject != '" + Dict.Anonymized + "';";

                var table = Database.GetInstance().ExecuteReadQuery(query);

                foreach (DataRow row in table.Rows)
                {
                    var subject = (string)row["subject"];
                    var time = DateTime.Parse((string)row["time"], CultureInfo.InvariantCulture);
                    var duration = Convert.ToInt32(row["durationInMins"], CultureInfo.InvariantCulture);

                    var t = new Tuple<string, DateTime, int>(subject, time, duration);
                    meetings.Add(t);
                }
            }
            catch (Exception e)
            {
                Logger.WriteToLogFile(e);
            }

            return meetings;
        }
开发者ID:sealuzh,项目名称:PersonalAnalytics,代码行数:33,代码来源:Queries.cs


示例20: SendJoinMail

        public Task SendJoinMail(
            string receipientAddress, string clusterAddress, int userPort, TimeSpan clusterTimeRemaining, DateTimeOffset clusterExpiration,
            IEnumerable<HyperlinkView> links)
        {
            string date = String.Format("{0:MMMM dd} at {1:H:mm:ss UTC}", clusterExpiration, clusterExpiration);
            string time = String.Format("{0} hour{1}, ", clusterTimeRemaining.Hours, clusterTimeRemaining.Hours == 1 ? "" : "s")
                          + String.Format("{0} minute{1}, ", clusterTimeRemaining.Minutes, clusterTimeRemaining.Minutes == 1 ? "" : "s")
                          + String.Format("and {0} second{1}", clusterTimeRemaining.Seconds, clusterTimeRemaining.Seconds == 1 ? "" : "s");

            string linkList = String.Join(
                "",
                links.Select(
                    x =>
                        String.Format("<li><a href=\"{0}\">{1}</a> - {2}</li>", x.Address, x.Text, x.Description)));

            return this.SendMessageAsync(
                new MailAddress(this.mailAddress, this.mailFrom),
                receipientAddress,
                this.mailSubject,
                this.joinMailTemplate
                    .Replace("__clusterAddress__", clusterAddress)
                    .Replace("__userPort__", userPort.ToString())
                    .Replace("__clusterExpiration__", date)
                    .Replace("__clusterTimeRemaining__", time)
                    .Replace("__links__", linkList));
        }
开发者ID:TylerAngell,项目名称:service-fabric-dotnet-management-party-cluster,代码行数:26,代码来源:SendGridMailer.cs



注:本文中的DateTimeOffset类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# DateTimeRange类代码示例发布时间:2022-05-24
下一篇:
C# DateTimeKind类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap