/// <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;
        }
        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;
        }
        /// <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);
        }
Example #4
0
 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));
 }
 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"),
     };
 }
        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();
        }
        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"));
        }
        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));
            }
        }
Example #9
0
        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());
        }
Example #10
0
 /// <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);
 }
            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
                };
            }
        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());
        }
 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());
 }
Example #14
0
        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;
        }
 /// <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);
 }
Example #16
0
        public IEnumerable<DateTimeOffset> GetAllTimesAfter(DateTimeOffset value)
        {
            DateTimeOffset temp = value.ToOffset(_offset);

            bool firstYear = true;
            bool firstMonth = true;
            bool firstDay = true;
            bool firstHour = true;
            bool firstMinute = true;
            bool firstSecond = true;
            bool firstMillisecond = true;
            bool firstMicrosecond = true;

            var years = _years != null ? _years.GetViewFrom(temp.Year).Values : Enumerable.Range(temp.Year, DateTimeOffset.MaxValue.Year - temp.Year + 1);

            foreach (var year in years)
            {
                firstYear &= year == value.Year;

                foreach (var month in firstYear ? _months.GetViewFrom(temp.Month).Values : _months.Values)
                {
                    firstMonth &= firstYear && month == value.Month;

                    foreach (var day in firstMonth ? _days.GetViewFrom(temp.Year, temp.Month, temp.Day).Values : _days.GetValues(year, month))
                    {
                        firstDay &= firstMonth && day == value.Day;

                        foreach (var hour in firstDay ? _hours.GetViewFrom(temp.Hour).Values : _hours.Values)
                        {
                            firstHour &= firstDay && hour == value.Hour;

                            foreach (var minute in firstHour ? _minutes.GetViewFrom(temp.Minute).Values : _minutes.Values)
                            {
                                firstMinute &= firstHour && minute == value.Minute;

                                foreach (var second in firstMinute ? _seconds.GetViewFrom(temp.Second).Values : _seconds.Values)
                                {
                                    firstSecond &= firstMinute && second == value.Second;

                                    foreach (var millisecond in firstSecond ? _milliseconds.GetViewFrom(temp.Millisecond).Values : _milliseconds.Values)
                                    {
                                        firstMillisecond &= firstSecond && millisecond == value.Millisecond;

                                        foreach (var microsecond in firstMillisecond ? _microseconds.GetViewFrom(temp.GetMicroseconds()).Values : _microseconds.Values)
                                        {
                                            firstMicrosecond &= firstMillisecond && microsecond == value.GetMicroseconds();

                                            foreach (var nanosecond in firstMicrosecond ? _nanoseconds.GetViewFrom(temp.GetNanoseconds()).Values : _nanoseconds.Values)
                                            {
                                                var next = new DateTimeOffset(year, month, day, hour, minute, second, millisecond, _offset).AddNanoseconds(microsecond * 1000 + nanosecond);
                                                if (next <= temp) { continue; }

                                                yield return next.ToOffset(value.Offset);
                                            }

                                            firstMicrosecond = false;
                                        }

                                        firstMillisecond = false;
                                    }

                                    firstSecond = false;
                                }

                                firstMinute = false;
                            }

                            firstHour = false;
                        }

                        firstDay = false;
                    }

                    firstMonth = false;
                }

                firstYear = false;
            }
        }
        public void back_and_forth_datetime_offset_conversions() {
            var dateTime = new DateTime(2012, 1, 2, 3, 4, 5, DateTimeKind.Local);
            // For illustration - dateTime in UTC is 1/2/2012 8:04:05 AM or +5 hrs
            var inUtc = TimeZone.CurrentTimeZone.ToUniversalTime(dateTime);
            // Existing Local Offset = -05:00
            var sourceTime = new DateTimeOffset(dateTime);
            // Converted to -02:00 Offset = Adds 3 hrs to sourceTime
            var targetTime = sourceTime.ToOffset(new TimeSpan(-2, 0, 0));

            Assert.Equal("1/2/2012 8:04:05 AM", inUtc.ToString());
            Assert.Equal("1/2/2012 3:04:05 AM -05:00", sourceTime.ToString());
            Assert.Equal("1/2/2012 6:04:05 AM -02:00", targetTime.ToString());
        }