当前位置: 首页>>代码示例>>C#>>正文


C# DateTimeOffset.ToOffset方法代码示例

本文整理汇总了C#中DateTimeOffset.ToOffset方法的典型用法代码示例。如果您正苦于以下问题:C# DateTimeOffset.ToOffset方法的具体用法?C# DateTimeOffset.ToOffset怎么用?C# DateTimeOffset.ToOffset使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在DateTimeOffset的用法示例。


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

示例1: GetCalendarEvents

        /// <summary>
        /// Returns a list of events given the start and end time, inclusive.
        /// </summary>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public IEnumerable<ICalendarEvent> GetCalendarEvents(DateTimeOffset startDate, DateTimeOffset endDate)
        {
            var calendarEventsService = _calendarService.Events.List(_calendarId);
            
            // Given the calendar time zone we're syncing to, determine how far backward and forward in time to go (approximately)
            calendarEventsService.TimeMin = startDate.ToOffset(_defaultCalendarTimeZone.BaseUtcOffset).DateTime;
            calendarEventsService.TimeMax = endDate.ToOffset(_defaultCalendarTimeZone.BaseUtcOffset).DateTime;

            // Get recurring events as single events (so we don't have to rely on the "master" recurring event)
            calendarEventsService.SingleEvents = true;

            // Get "deleted" events, since Google only performs soft deletes, so that we can "undelete" if necessary.
            calendarEventsService.ShowDeleted = true;

            // Execute the command
            var calendarEvents = calendarEventsService.Execute();

            var returnEvents = new List<ICalendarEvent>();

            // Iterate
            foreach (var calendarEvent in calendarEvents.Items)
            {
                var returnEvent = _calendarEventTransformer.ConvertToCalendarEvent(calendarEvent);
                returnEvents.Add(returnEvent);
            }

            return returnEvents;
        }
开发者ID:rkeilty,项目名称:RK.Calendar.Sync,代码行数:34,代码来源:GoogleCalendar.cs

示例2: ConvertDictionaryToClassDataContract

        public static object ConvertDictionaryToClassDataContract(DataContractJsonSerializer serializer, ClassDataContract dataContract, Dictionary<string, object> deserialzedValue, XmlObjectSerializerReadContextComplexJson context)
        {
            if (deserialzedValue == null)
            {
                return null;
            }

            if (dataContract.UnderlyingType == Globals.TypeOfDateTimeOffsetAdapter)
            {
                var tuple = deserialzedValue["DateTime"] as Tuple<DateTime, string>;
                DateTimeOffset dto = new DateTimeOffset(tuple != null ? tuple.Item1 : (DateTime)deserialzedValue["DateTime"]);
                return dto.ToOffset(new TimeSpan(0, (int)deserialzedValue["OffsetMinutes"], 0));
            }

            object serverTypeStringValue;
            if (deserialzedValue.TryGetValue(JsonGlobals.ServerTypeString, out serverTypeStringValue))
            {
                dataContract = ResolveDataContractFromTypeInformation(serverTypeStringValue.ToString(), dataContract, context);
            }

            object o = CreateInstance(dataContract);

            CheckDuplicateNames(dataContract);
            DataContractJsonSerializer.InvokeOnDeserializing(o, dataContract, context);
            ReadClassDataContractMembers(serializer, dataContract, deserialzedValue, o, context);
            DataContractJsonSerializer.InvokeOnDeserialized(o, dataContract, context);
            if (dataContract.IsKeyValuePairAdapter)
            {
                return dataContract.GetKeyValuePairMethodInfo.Invoke(o, Array.Empty<Type>());
            }
            return o;
        }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:32,代码来源:ObjectToDataContractConverterHelper.cs

示例3: GetCalendarEvents

        /// <summary>
        /// Returns a list of events given the start and end time, inclusive.
        /// </summary>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public IEnumerable<ICalendarEvent> GetCalendarEvents(DateTimeOffset startDate, DateTimeOffset endDate)
        {
            // Initialize the calendar folder object with only the folder ID.
            var propertiesToGet = new PropertySet(PropertySet.IdOnly);
            propertiesToGet.RequestedBodyType = BodyType.Text;

            var calendar = CalendarFolder.Bind(_exchangeService, WellKnownFolderName.Calendar, propertiesToGet);
            
            // Set the start and end time and number of appointments to retrieve.
            var calendarView = new CalendarView(
                startDate.ToOffset(_exchangeService.TimeZone.BaseUtcOffset).DateTime,
                endDate.ToOffset(_exchangeService.TimeZone.BaseUtcOffset).DateTime,
                MAX_EVENTS_TO_RETRIEVE);

            // Retrieve a collection of appointments by using the calendar view.
            var appointments = calendar.FindAppointments(calendarView);

            // Get specific properties.
            var appointmentSpecificPropertiesToGet = new PropertySet(PropertySet.FirstClassProperties);
            appointmentSpecificPropertiesToGet.AddRange(NonFirstClassAppointmentProperties);
            appointmentSpecificPropertiesToGet.RequestedBodyType = BodyType.Text;
            _exchangeService.LoadPropertiesForItems(appointments, appointmentSpecificPropertiesToGet);

            return TransformExchangeAppointmentsToGenericEvents(appointments);
        }
开发者ID:rkeilty,项目名称:RK.Calendar.Sync,代码行数:31,代码来源:ExchangeCalendar.cs

示例4: ToClientTimeZone

 public static DateTimeOffset ToClientTimeZone(long ticks, int zona)
 {
     var dt = new DateTime(ticks, DateTimeKind.Utc);
     var tz = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(b => b.BaseUtcOffset.Hours == zona);
     var utcOffset = new DateTimeOffset(dt, TimeSpan.Zero);
     return utcOffset.ToOffset(tz.GetUtcOffset(utcOffset));
 }
开发者ID:SandyMG,项目名称:initial-chumaster,代码行数:7,代码来源:Util.cs

示例5: TimeContext

 private object TimeContext(DateTimeOffset time, string place,  double offset)
 {
     DateTimeOffset localtime = time.ToOffset(TimeSpan.FromHours(offset));
     return new {
         Place = place,
         Time = localtime.ToString("HH:mm:ss"),
         Date = localtime.ToString("yyyy-MM-dd"),
     };
 }
开发者ID:eiel,项目名称:WorldWatch-WinStore,代码行数:9,代码来源:MainPage.xaml.cs

示例6: ToUtcISOString

        public static string ToUtcISOString(this DateTime dt, string sourceTzID)
        {
            if (dt != null
                && !string.IsNullOrEmpty(sourceTzID)
                )
            {
                TimeZoneInfo tzSource = TimeZoneInfo.FindSystemTimeZoneById(sourceTzID);
                TimeSpan tsSource = new TimeSpan(tzSource.BaseUtcOffset.Hours, tzSource.BaseUtcOffset.Minutes, tzSource.BaseUtcOffset.Seconds);

                DateTimeOffset sourceTime, baseTime;
                sourceTime = new DateTimeOffset(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, tsSource);//source time
                baseTime = sourceTime.ToOffset(TimeSpan.Zero);//offset 0 time
                return baseTime.DateTime.ToString("yyyy-MM-ddTHH:mm:ss.fff") + "+00:00";
            }
            return dt.ToUtcISOString();
        }
开发者ID:phtmahajan,项目名称:ShoppingCart,代码行数:16,代码来源:DateTimeExtensions.cs

示例7: ConvertDateTimeOffsetToLocal

        public void ConvertDateTimeOffsetToLocal(int offset)
        {
            // Arrange
            DateTimeOffsetToLocalConverter converter = new DateTimeOffsetToLocalConverter();
            DateTime utcDateTime = new DateTime(2013, 4, 16, 3, 55, 30, DateTimeKind.Utc);
            DateTimeOffset utcOffset = new DateTimeOffset(utcDateTime);
            DateTimeOffset expected = utcDateTime.ToLocalTime();

            var date = utcOffset.ToOffset(new TimeSpan(offset, 0, 0));

            // Act
            var actual = (DateTimeOffset)converter.Convert(date, typeof(DateTimeOffset), null, CultureInfo.InvariantCulture);

            // Assert that the offsets are identical
            Assert.True(expected.Offset.CompareTo(actual.Offset) == 0);

            // Assert that the dates display the same
            Assert.Equal<string>(expected.ToString("d"), actual.ToString("d"));
        }
开发者ID:Newtopian,项目名称:nuget,代码行数:19,代码来源:DateTimeOffsetToLocalConverterTest.cs

示例8: GetDateTimeOffset

        public static DateTimeOffset GetDateTimeOffset(DateTimeOffsetAdapter value)
        {
            try
            {
                switch (value.UtcDateTime.Kind)
                {
                    case DateTimeKind.Unspecified:
                        return new DateTimeOffset(value.UtcDateTime, new TimeSpan(0, value.OffsetMinutes, 0));

                    //DateTimeKind.Utc and DateTimeKind.Local
                    //Read in deserialized DateTime portion of the DateTimeOffsetAdapter and convert DateTimeKind to Unspecified.
                    //Apply ofset information read from OffsetMinutes portion of the DateTimeOffsetAdapter.
                    //Return converted DateTimeoffset object.
                    default:
                        DateTimeOffset deserialized = new DateTimeOffset(value.UtcDateTime);
                        return deserialized.ToOffset(new TimeSpan(0, value.OffsetMinutes, 0));
                }
            }
            catch (ArgumentException exception)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value.ToString(CultureInfo.InvariantCulture), "DateTimeOffset", exception));
            }
        }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:23,代码来源:DateTimeOffsetAdapter.cs

示例9: HasTime

        public bool HasTime(DateTimeOffset value)
        {
            DateTimeOffset temp = value.ToOffset(_offset);

            return
                (_years == null || _years.Contains(temp.Year)) &&
                _months.Contains(temp.Month) &&
                _days.Contains(temp.Year, temp.Month, temp.Day) &&
                _hours.Contains(temp.Hour) &&
                _minutes.Contains(temp.Minute) &&
                _seconds.Contains(temp.Second) &&
                _milliseconds.Contains(temp.Millisecond) &&
                _microseconds.Contains(temp.GetMicroseconds()) &&
                _nanoseconds.Contains(temp.GetNanoseconds());
        }
开发者ID:rgonek,项目名称:crongadgetry,代码行数:15,代码来源:CronExpression.cs

示例10: ToSpecificTimeZone

 /// <summary>
 /// To the specific time zone.
 /// </summary>
 /// <param name="timeZoneId">The time zone id</param>
 /// <param name="dateTime">The date time</param>
 /// <returns>The converted DateTime object</returns>
 public static DateTimeOffset ToSpecificTimeZone(string timeZoneId, DateTimeOffset dateTime)
 {
     TimeZoneInfo timeZoneInfo = DateTimeHelpers.GetTimeZone(timeZoneId);
     return dateTime.ToOffset(timeZoneInfo.BaseUtcOffset);
 }
开发者ID:eserozvataf,项目名称:tasslehoff,代码行数:11,代码来源:DateTimeHelpers.cs

示例11: ToDateTimeOffsetTz

            public static DateTimeOffsetTz ToDateTimeOffsetTz(DateTime dateTime, int offsetInt) {
                var sourceDateTimeOffset = new DateTimeOffset(dateTime);
                var targetDateTimeOffset = sourceDateTimeOffset.ToOffset(new TimeSpan(offsetInt, 0, 0));
                // this isn't right because baseutcoffset is not tz/dst aware
                // assumes only one so it's like UTC-5, doesn't change at DST
                // we don't have a tzinfo object yet to use GetUtcOffset(DateTimeOffset) either
                var tzInfo = TimeZoneInfo.GetSystemTimeZones()
                    .FirstOrDefault(x => x.BaseUtcOffset == targetDateTimeOffset.Offset);

                return new DateTimeOffsetTz() {
                    DateTime = targetDateTimeOffset.DateTime,
                    DateTimeOffset = targetDateTimeOffset,
                    TimeZoneInfo = tzInfo
                };
            }
开发者ID:heynickc,项目名称:noda_datetimes_deepdive,代码行数:15,代码来源:WithBCLDateTime.cs

示例12: try_convert_datetimes_with_offset_integer_only

        public void try_convert_datetimes_with_offset_integer_only() {
            var sourceDateTime = new DateTime(2012, 1, 2, 3, 4, 5, DateTimeKind.Local);
            var offsetInt = 5;

            var sourceDateTimeOffset = new DateTimeOffset(sourceDateTime);
            var targetDateTimeOffset = sourceDateTimeOffset.ToOffset(new TimeSpan(offsetInt, 0, 0));

            var tzInfos = TimeZoneInfo.GetSystemTimeZones();
            var tzInfo = tzInfos.Where(x => x.BaseUtcOffset == targetDateTimeOffset.Offset).Select(y => y.DisplayName).FirstOrDefault();
            //_output.WriteLine(tzInfos.ToJson());
            Assert.Equal("(UTC+05:00) Ashgabat, Tashkent", tzInfo);
            Assert.Equal("1/2/2012 1:04:05 PM +05:00", targetDateTimeOffset.ToString());
        }
开发者ID:heynickc,项目名称:noda_datetimes_deepdive,代码行数:13,代码来源:WithBCLDateTime.cs

示例13: datetimeoffset_conversion_with_tooffset

 public void datetimeoffset_conversion_with_tooffset() {
     var dateTime = new DateTime(2012, 1, 2, 3, 4, 5, DateTimeKind.Local);
     var sourceTime = new DateTimeOffset(dateTime);
     var targetTime = sourceTime.ToOffset(new TimeSpan(-8, 0, 0));
     Assert.Equal("1/2/2012 12:04:05 AM -08:00", targetTime.ToString());
 }
开发者ID:heynickc,项目名称:noda_datetimes_deepdive,代码行数:6,代码来源:WithBCLDateTime.cs

示例14: GetStopTimes

        public override List<StopTime> GetStopTimes(string stopID)
        {
            System.Net.WebClient client = new System.Net.WebClient();
            var jsonResult = client.DownloadString("http://api.wmata.com/StationPrediction.svc/json/GetPrediction/" + stopID + "?api_key=" + APIKey);

            List<StopTime> result = new List<StopTime>();

            var data = Json.Decode(jsonResult);

            if (data != null)
            {
                foreach (var r in data.Trains)
                {
                    if (r.Min != "")
                    {
                        StopTime t = new StopTime();

                        t.RouteShortName = r.Line;
                        t.RouteLongName = r.Line;

                        var utc = new DateTimeOffset(DateTime.UtcNow, TimeSpan.Zero);
                        var now = utc.ToOffset(this.TransitAgency.FriendlyTimeZone.GetUtcOffset(utc));

                        if (r.Min.ToString() == "ARR" ||
                            r.Min.ToString() == "BRD")
                            t.ArrivalTime = now.DateTime.ToString("hh:mm tt");
                        else
                            t.ArrivalTime = now.AddMinutes(Convert.ToInt32(r.Min.ToString())).DateTime.ToString("hh:mm tt");

                        t.DepartureTime = t.ArrivalTime;
                        t.Type = "realtime";

                        if ((from x in result where x.RouteShortName == t.RouteShortName select x).Count() < 2)
                            result.Add(t);
                    }
                }
            }

            jsonResult = client.DownloadString("http://api.wmata.com/Bus.svc/json/JStopSchedule?stopId=" + stopID + "&api_key=" + APIKey);

            data = Json.Decode(jsonResult);

            if (data != null)
            {
                foreach (var r in data.ScheduleArrivals)
                {
                    StopTime t = new StopTime();
                    t.RouteShortName = r.RouteID;
                    t.RouteLongName = r.RouteID;
                    t.ArrivalTime = DateTime.ParseExact(r.ScheduleTime.ToString(), "s", new System.Globalization.CultureInfo("en-US")).TimeOfDay;
                    t.DepartureTime = t.ArrivalTime;
                    t.Type = "scheduled";

                    if ((from x in result where x.RouteShortName == t.RouteShortName select x).Count() < 2)
                        result.Add(t);
                }
            }

            return result;
        }
开发者ID:mbmccormick,项目名称:OneTransitAPI,代码行数:60,代码来源:WMATA.cs

示例15: Bind

 /// <summary>
 /// Bind the parameter to an <see cref="DateTimeOffset"/>.
 /// </summary>
 /// <param name="This">The bind parameter.</param>
 /// <param name="value">A <see cref="DateTimeOffset"/>.</param>
 public static void Bind(this IBindParameter This, DateTimeOffset value)
 {
     Contract.Requires(This != null);
     This.Bind(value.ToOffset(TimeSpan.Zero).Ticks);
 }
开发者ID:matrostik,项目名称:SQLitePCL.pretty,代码行数:10,代码来源:BindParameter.cs


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