GetUtcOffset() public method

public GetUtcOffset ( System.DateTime dateTime ) : System.TimeSpan
dateTime System.DateTime
return System.TimeSpan
Esempio n. 1
0
        private static void Dump(TimeZoneInfo zone, Options options, TextWriter writer)
        {
            writer.Write($"{zone.Id}\n");

            // This will be a bit odd using Windows time zones, as most have permanent
            // daylight saving rules... but for tz data, it should be okay.
            var initial = new DateTimeOffset(2, 1, 1, 0, 0, 0, 0, TimeSpan.Zero);
            var initialOffset = zone.GetUtcOffset(initial);
            var initialDaylight = zone.IsDaylightSavingTime(initial);
            writer.Write("Initially:           {0} {1} {2}\n",
                (initialOffset.Ticks >= 0 ? "+" : "-") + initialOffset.ToString("hh':'mm':'ss", CultureInfo.InvariantCulture),
                initialDaylight ? "daylight" : "standard",
                initialDaylight ? zone.DaylightName : zone.StandardName);

            int fromYear = options.FromYear ?? 1800;
            DateTimeOffset start = new DateTimeOffset(fromYear, 1, 1, 0, 0, 0, TimeSpan.Zero);
            DateTimeOffset end = new DateTimeOffset(options.ToYear, 1, 1, 0, 0, 0, TimeSpan.Zero);

            DateTimeOffset? transition = GetNextTransition(zone, start.AddTicks(-1), end);
            while (transition != null)
            {
                var offset = zone.GetUtcOffset(transition.Value);
                var isDaylight = zone.IsDaylightSavingTime(transition.Value);
                // It's unfortunate that TimeZoneInfo doesn't support the idea of different names
                // for different periods in history. Never mind - this is better than nothing,
                // for diagnostic purposes.
                writer.Write("{0} {1} {2} {3}\n",
                    transition.Value.ToString("yyyy-MM-dd HH:mm:ss'Z'", CultureInfo.InvariantCulture),
                    (offset.Ticks >= 0 ? "+" : "-") + offset.ToString("hh':'mm':'ss", CultureInfo.InvariantCulture),
                    isDaylight ? "daylight" : "standard",
                    isDaylight ? zone.DaylightName : zone.StandardName);
                transition = GetNextTransition(zone, transition.Value, end);
            }
            writer.Write("\n");
        }
Esempio n. 2
0
        /// <summary>
        /// TimeZoneInfo.GetUtcOffset(DateTimeOffset) is not supported under mono
        /// </summary>
        /// <param name="dateTimeOffset"></param>
        /// <param name="timeZoneInfo"></param>
        /// <returns></returns>
        public static TimeSpan GetUtcOffset(DateTimeOffset dateTimeOffset, TimeZoneInfo timeZoneInfo)
        {
            if (QuartzEnvironment.IsRunningOnMono)
            {
                return timeZoneInfo.GetUtcOffset(dateTimeOffset.UtcDateTime);
            }

            return timeZoneInfo.GetUtcOffset(dateTimeOffset);
        }
Esempio n. 3
0
        public void NowEasternIsNowUtcMinusOffset()
        {
            var utc_now     = DateTime.UtcNow;
            var eastern_now = TimeZoneInfo.ConvertTimeFromUtc(utc_now, eastern_tzinfo);

            Assert.AreEqual(utc_now - eastern_now, -eastern_tzinfo.GetUtcOffset(utc_now));
        }
Esempio n. 4
0
		/// <summary>
		/// This method will return a signed four digit integer indicating the
		/// GMT offset for the given TimeZoneInfo when applied to the given DateTime.
		/// This is the HL7 Offset format in integer representation.
		/// </summary>
		public static int GetGMTOffset(TimeZoneInfo timeZone, DateTime time)
		{
			var gmtOffSet = timeZone.GetUtcOffset(time);

			//return the offset value HL7 format
			return gmtOffSet.Hours*100 + gmtOffSet.Minutes;
		}
Esempio n. 5
0
        public override TimeSpan GetUtcOffset(DateTime dateTime)
        {
            if (dateTime.Kind == DateTimeKind.Utc)
            {
                return(TimeSpan.Zero);
            }

            return(LocalTimeZone.GetUtcOffset(dateTime));
        }
Esempio n. 6
0
 private static TimeSpan DetectStandardOffset(TimeZoneInfo zone, TimeZoneInfo.AdjustmentRule rule)
 {
     var offset = zone.GetUtcOffset(rule.DateStart);
     if (zone.IsDaylightSavingTime(rule.DateStart))
     {
         offset -= rule.DaylightDelta;
     }
     return offset;
 }
Esempio n. 7
0
        public static double CalcTimeZoneOffset(TimeZoneInfo tzi, DateTime userNow, out string timezoneName)
        {
            double offset = tzi.GetUtcOffset(userNow).TotalHours;
            var hour = (int)Math.Truncate(offset);
            string oldname = tzi.DisplayName;
            oldname = oldname.Remove(0, oldname.IndexOf(')') + 1);
            timezoneName = "(UTC" + hour.ToString("+00;-00") + ":" + ((int)((offset - hour) * 60)).ToString("00") + ") " + oldname;

            return offset;
        }
Esempio n. 8
0
 public static XElement TimeZoneToXml(TimeZoneInfo aTimeZoneInfo, DateTime aNow)
 {
     return new XElement("timezone",
         new XElement("name", aTimeZoneInfo.DisplayName),
         new XElement("daylightName", aTimeZoneInfo.DaylightName),
         new XElement("standardName", aTimeZoneInfo.StandardName),
         new XElement("hasDaylight", aTimeZoneInfo.SupportsDaylightSavingTime ? "yes" : "no"),
         new XElement("currentOffset", OffsetToString(aTimeZoneInfo.GetUtcOffset(aNow))),
         new XElement("isDaylight", aTimeZoneInfo.IsDaylightSavingTime(aNow) ? "yes" : "no"));
 }
 public ServerTimeZoneInfo(TimeZoneInfo timeZone, TimeZoneInfo localTimeZone, DateTime now, DateTime utcNow)
 {
     ServerTimeZone = string.Format(CultureInfo.InvariantCulture, "{0} ({1})",
                                    localTimeZone.StandardName,
                                    localTimeZone.GetUtcOffset(now));
     ServerTime = now.ToString("yyyy/MM/dd hh:mm tt", CultureInfo.InvariantCulture);
     ServerUtcTime = utcNow.ToString("yyyy/MM/dd hh:mm tt", CultureInfo.InvariantCulture);
     CurrentTime = TimeZoneInfo.ConvertTimeFromUtc(utcNow, timeZone).ToString("yyyy/MM/dd hh:mm tt",
                                                                              CultureInfo.InvariantCulture);
 }
        public DateTimeOffset ConvertDateTimeOffsetTo(TimeZoneInfo timeZoneInfo, DateTimeOffset dateTimeOffset, int hour = 0, int minute = 0, int second = 0)
        {
            return new DateTimeOffset(dateTimeOffset.Year, dateTimeOffset.Month, dateTimeOffset.Day, hour, minute, second, timeZoneInfo.GetUtcOffset(dateTimeOffset));

            //both of these implemenations lose the ability to specificy the hour, minute and second unless the given dateTimeOffset value being passed into this method
            //already has those values set
            //1.
            //return TimeZoneInfo.ConvertTime(dateTimeOffset, timeZoneInfo);
            //2.
            //var timeSpan = timeZoneInfo.GetUtcOffset(dateTimeOffset);
            //return dateTimeOffset.ToOffset(timeSpan);
        }
        ///<summary>
        ///Converts a regular DateTime to a RFC822 date string.
        ///</summary>
        ///<returns>The specified date formatted as a RFC822 date string.</returns>
        public static string ToRfc2822Date(this DateTime date,TimeZoneInfo timeZoneInfo)
        {
            int offset = timeZoneInfo.GetUtcOffset(date).Hours;
            string timeZone = "+" + offset.ToString().PadLeft(2, '0');

            if (offset < 0)
            {
                int i = offset * -1;
                timeZone = "-" + i.ToString().PadLeft(2, '0');
            }

            return date.ToString("ddd, dd MMM yyyy HH:mm:ss" + timeZone.PadRight(5, '0'), CultureInfo.InvariantCulture);
        }
Esempio n. 12
0
 private static DateTimeOffset? GetNextTransition(TimeZoneInfo zone, DateTimeOffset start, DateTimeOffset end)
 {
     TimeSpan startOffset = zone.GetUtcOffset(start);
     bool startDaylight = zone.IsDaylightSavingTime(start);
     DateTimeOffset now = start.AddDays(1);
     while (now <= end)
     {
         if (zone.GetUtcOffset(now) != startOffset || zone.IsDaylightSavingTime(now) != startDaylight)
         {
             // Right, so there's a transition strictly after now - (one day), and less than or equal to now. Binary search...
             long upperInclusiveTicks = now.Ticks;
             long lowerExclusiveTicks = now.AddDays(-1).Ticks;
             while (upperInclusiveTicks > lowerExclusiveTicks + 1)
             {
                 long candidateTicks = (upperInclusiveTicks + lowerExclusiveTicks) / 2;
                 var candidateDto = new DateTimeOffset(candidateTicks, TimeSpan.Zero);
                 if (zone.GetUtcOffset(candidateDto) != startOffset || zone.IsDaylightSavingTime(candidateDto) != startDaylight)
                 {
                     // Still seeing a difference: look earlier
                     upperInclusiveTicks = candidateTicks;
                 }
                 else
                 {
                     // Same as at start of day: look later
                     lowerExclusiveTicks = candidateTicks;
                 }
             }
             // If we turn out to have hit the end point, we're done without a final transition.
             return upperInclusiveTicks == end.Ticks
                 ? (DateTimeOffset?)null
                 : new DateTimeOffset(upperInclusiveTicks, TimeSpan.Zero);
         }
         now = now.AddDays(1);
     }
     return null;
 }
Esempio n. 13
0
 public static DateTimeOffset ReadStringWithTimeZone(DateTime EnteredDate, TimeZoneInfo tzi)
 {
     DateTimeOffset cvUTCToTZI = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, tzi);
     DateTimeOffset cvParsedDate = DateTimeOffset.MinValue;
     DateTimeOffset.TryParse(EnteredDate + " " + cvUTCToTZI.ToString("zzz"), out cvParsedDate);
     if (tzi.SupportsDaylightSavingTime)
     {
         TimeSpan getDiff = tzi.GetUtcOffset(cvParsedDate);
         string MakeFinalOffset = (getDiff.Hours < 0 ? "-" : "+") + (getDiff.Hours > 9 ? "" : "0") + getDiff.Hours + ":" + (getDiff.Minutes > 9 ? "" : "0") + getDiff.Minutes;
         DateTimeOffset.TryParse(EnteredDate + " " + MakeFinalOffset, out cvParsedDate);
         return cvParsedDate;
     }
     else
     {
         return cvParsedDate;
     }
 }
		static internal TimeSpan GetUtcOffsetFromUtc (DateTime time, TimeZoneInfo zone, out Boolean isDaylightSavings, out Boolean isAmbiguousLocalDst)
		{
			isDaylightSavings = false;
			isAmbiguousLocalDst = false;
			TimeSpan baseOffset = zone.BaseUtcOffset;

			if (zone.IsAmbiguousTime (time)) {
				isAmbiguousLocalDst = true;
				return baseOffset;
			}

			return zone.GetUtcOffset (time, out isDaylightSavings);
		}
        /// <summary>
        /// Handles with a given text matches the Expression4 field.
        /// </summary>
        /// <param name="nameValueCollection">A collection of values from the named capture groups.</param>
        /// <param name="results">The results.</param>
        private void Expression4Handler(NameValueCollection nameValueCollection, TimeZoneInfo timeZone, TextToScheduleResults results)
        {
            // every [n] (days|weeks|months|years) (from [date]) (at [time])

            string amountString = nameValueCollection["AMOUNT"];
            string intervalString = nameValueCollection["INTERVALUNIT"];

            var dateSpec = nameValueCollection["DATESPEC"];
            var dayOfWeekSpecs = nameValueCollection.GetValues("DAYOFWEEK");
            var timesToFire = nameValueCollection.GetValues("TIME");

            DateTime? triggerStartTime = null;

            if (dayOfWeekSpecs != null && GrammarHelper.GetIntervalUnitValueFromString(intervalString) != IntervalUnit.Week)
            {
                throw new Exception("You should only specify a day of the week, when you are using the \"week\" time interval.");
            }

            if (timesToFire == null) // if times are not specified assume midnight
                timesToFire = new string[] { "00:00" };

            foreach (var timeString in timesToFire)
            {
                if (dateSpec != null || timeString != null)
                    triggerStartTime = GrammarHelper.GetDateTimeFromDateSpecAndTime(dateSpec, timeString);

                if (dayOfWeekSpecs != null)
                {
                    var dayOfWeeks = GrammarHelper.GetDayOfWeekValues(dayOfWeekSpecs);
                    foreach (var dayOfWeek in dayOfWeeks)
                    {
                        if (triggerStartTime == null)
                            triggerStartTime = SystemTime.Now().DateTime;

                        DateTime dowTriggerStartTime = triggerStartTime.Value;
                        //seek
                        dowTriggerStartTime = SeekForwardToNextDayOfWeek(dowTriggerStartTime, dayOfWeek);

                        TriggerBuilder triggerBuilder = TriggerBuilder.Create();
                        triggerBuilder.WithSchedule(CreateScheduleWithAmountAndIntervalUnit(amountString, intervalString, timeZone));
                        triggerBuilder.StartAt(new DateTimeOffset(dowTriggerStartTime, timeZone.GetUtcOffset(dowTriggerStartTime)));

                        results.Add(triggerBuilder, null);
                    }
                }
                else
                {
                    TriggerBuilder triggerBuilder = TriggerBuilder.Create();
                    triggerBuilder.WithSchedule(CreateScheduleWithAmountAndIntervalUnit(amountString, intervalString, timeZone));

                    //start on from time
                    if (triggerStartTime != null)
                        triggerBuilder.StartAt(new DateTimeOffset(triggerStartTime.Value, timeZone.GetUtcOffset(triggerStartTime.Value)));

                    results.Add(triggerBuilder, null);
                }
            }
        }
        /// <summary>
        /// Handles with a given text matches the Expression1 field.
        /// </summary>
        /// <param name="nameValueCollection">A collection of values from the named capture groups.</param>
        /// <param name="results">The results.</param>
        private void Expression1Handler(NameValueCollection nameValueCollection, TimeZoneInfo timeZone, TextToScheduleResults results)
        {
            var amountString = nameValueCollection["AMOUNT"];
            var intervalUnitString = nameValueCollection["INTERVALUNIT"];
            var startDateString = nameValueCollection["DATESPEC"];

            var time = nameValueCollection["TIME"];
            var fromTime = nameValueCollection["FROMTIME"];
            var toTime = nameValueCollection["TOTIME"];

            var dayOfWeekSpecs = nameValueCollection.GetValues("DAYOFWEEK");
            var monthSpecs = nameValueCollection.GetValues("MONTH");

            DateTime? triggerStartTime = null;

            ICalendar calendar = null;

            //DAY OF WEEK SPECS
            if (dayOfWeekSpecs != null)
            {
                calendar = BuildCalendarOnDayOfWeek(calendar, dayOfWeekSpecs, timeZone);
            }

            //MONTH SPECS
            if (monthSpecs != null)
            {
                calendar = BuildCalendarOnMonths(calendar, monthSpecs, timeZone);
            }


            //TIME (single or range)

            //check for ranged time
            if (fromTime != null && toTime != null)
            {
                calendar = BuildCalendarOnTimeRange(calendar, fromTime, toTime, timeZone);

                //set the start date as the from time
                DateTime? fromTimeStartDate = GrammarHelper.GetTimeFromTimeString(fromTime);
                triggerStartTime = fromTimeStartDate;
            }
            //is regular time, process as single time provided
            else if (time != null)
            {
                DateTime? timeStartDate = GrammarHelper.GetTimeFromTimeString(time);
                triggerStartTime = timeStartDate;
            }

            //BUILD TRIGGER
            TriggerBuilder triggerBuilder = TriggerBuilder.Create();

            //set schedule
            triggerBuilder.WithSchedule(CreateScheduleWithAmountAndIntervalUnit(amountString, intervalUnitString, timeZone));


            //start on from time
            if (triggerStartTime != null)
                triggerBuilder.StartAt(new DateTimeOffset(triggerStartTime.Value, timeZone.GetUtcOffset(triggerStartTime.Value)));

            results.Add(triggerBuilder, calendar);
        }
Esempio n. 17
0
    private static DateTime convertTimeZoneTimeToGmt(DateTime timeZoneTime_, TimeZoneInfo tz_)
    {
      var offset = tz_.GetUtcOffset(timeZoneTime_.Date);

      return timeZoneTime_.Add(-offset);
    }
        public void GuessZoneIdByTransitionsUncached(TimeZoneInfo bclZone)
        {
            // As of October 17th 2013, the Windows time zone database hasn't noticed that
            // Morocco delayed the DST transition in 2013, so we end up with UTC. It's
            // annoying, but it's not actually a code issue. Just ignore it for now. We
            // should check this periodically and remove the hack when it works again.
            // Likewise Libya has somewhat odd representation in the BCL. Worth looking at more closely later.
            if (bclZone.Id == "Morocco Standard Time" || bclZone.Id == "Libya Standard Time")
            {
                return;
            }
            string id = TzdbDateTimeZoneSource.Default.GuessZoneIdByTransitionsUncached(bclZone);

            // Unmappable zones may not be mapped, or may be mapped to something reasonably accurate.
            // We don't mind either way.
            if (!TzdbDateTimeZoneSource.Default.WindowsMapping.PrimaryMapping.ContainsKey(bclZone.Id))
            {
                return;
            }

            Assert.IsNotNull(id);
            var tzdbZone = TzdbDateTimeZoneSource.Default.ForId(id);

            var thisYear = SystemClock.Instance.GetCurrentInstant().InUtc().Year;
            LocalDate? lastIncorrectDate = null;
            Offset? lastIncorrectBclOffset = null;
            Offset? lastIncorrectTzdbOffset = null;

            int total = 0;
            int correct = 0;
            // From the start of this year to the end of next year, we should have an 80% hit rate or better.
            // That's stronger than the 70% we limit to in the code, because if it starts going between 70% and 80% we
            // should have another look at the algorithm. (And this is dealing with 80% of days, not 80% of transitions,
            // so it's not quite equivalent anyway.)
            for (var date = new LocalDate(thisYear, 1, 1); date.Year < thisYear + 2; date = date.PlusDays(1))
            {
                Instant startOfUtcDay = date.AtMidnight().InUtc().ToInstant();
                Offset tzdbOffset = tzdbZone.GetUtcOffset(startOfUtcDay);
                Offset bclOffset = Offset.FromTimeSpan(bclZone.GetUtcOffset(startOfUtcDay.ToDateTimeOffset()));
                if (tzdbOffset == bclOffset)
                {
                    correct++;
                }
                else
                {
                    // Useful for debugging (by having somewhere to put a breakpoint) as well as for the message.
                    lastIncorrectDate = date;
                    lastIncorrectBclOffset = bclOffset;
                    lastIncorrectTzdbOffset = tzdbOffset;
                }
                total++;
            }
            Assert.That(correct * 100.0 / total, Is.GreaterThanOrEqualTo(75.0),
                "Last incorrect date for {0} vs {1}: {2} (BCL: {3}; TZDB: {4})",
                bclZone.Id,
                id,
                lastIncorrectDate, lastIncorrectBclOffset, lastIncorrectTzdbOffset);
        }
Esempio n. 19
0
        internal static string FormatDate(string format, DateTime utc, TimeZoneInfo zone)
        {
            Debug.Assert(zone != null);

            if (format == null)
                return string.Empty;

            DateTime local = TimeZoneInfo.ConvertTimeFromUtc(utc, zone);

            // here we are creating output string
            StringBuilder result = new StringBuilder();
            bool escape = false;

            foreach (char ch in format)
            {
                if (escape)
                {
                    result.Append(ch);
                    escape = false;
                    continue;
                }

                switch (ch)
                {
                    case 'a':
                        // Lowercase Ante meridiem and Post meridiem - am or pm
                        result.Append(local.ToString("tt", DateTimeFormatInfo.InvariantInfo).ToLowerInvariant());
                        break;

                    case 'A':
                        // Uppercase Ante meridiem and Post meridiem - AM or PM
                        result.Append(local.ToString("tt", DateTimeFormatInfo.InvariantInfo));
                        break;

                    case 'B':
                        // Swatch Beat (Internet Time) - 000 through 999
                        result.AppendFormat("{0:000}", GetSwatchBeat(utc));
                        break;

                    case 'c':
                        {
                            // ISO 8601 date (added in PHP 5) 2004-02-12T15:19:21+00:00
                            result.Append(local.ToString("yyyy-MM-dd'T'HH:mm:ss", DateTimeFormatInfo.InvariantInfo));

                            TimeSpan offset = zone.GetUtcOffset(local);
                            result.AppendFormat("{0}{1:00}:{2:00}", (offset.Ticks < 0) ? ""/*offset.Hours already < 0*/ : "+", offset.Hours, offset.Minutes);
                            break;
                        }

                    case 'd':
                        // Day of the month, 2 digits with leading zeros - 01 to 31
                        result.Append(local.ToString("dd", DateTimeFormatInfo.InvariantInfo));
                        break;

                    case 'e':
                        // Timezone identifier (added in PHP 5.1.0)
                        result.Append(zone.Id);
                        break;

                    case 'D':
                        // A textual representation of a day, three letters - Mon through Sun
                        result.Append(local.ToString("ddd", DateTimeFormatInfo.InvariantInfo));
                        break;

                    case 'F':
                        // A full textual representation of a month, such as January or March - January through December
                        result.Append(local.ToString("MMMM", DateTimeFormatInfo.InvariantInfo));
                        break;

                    case 'g':
                        // 12-hour format of an hour without leading zeros - 1 through 12
                        result.Append(local.ToString("%h", DateTimeFormatInfo.InvariantInfo));
                        break;

                    case 'G':
                        // 24-hour format of an hour without leading zeros - 0 through 23
                        result.Append(local.ToString("%H", DateTimeFormatInfo.InvariantInfo));
                        break;

                    case 'h':
                        // 12-hour format of an hour with leading zeros - 01 through 12
                        result.Append(local.ToString("hh", DateTimeFormatInfo.InvariantInfo));
                        break;

                    case 'H':
                        // 24-hour format of an hour with leading zeros - 00 through 23
                        result.Append(local.ToString("HH", DateTimeFormatInfo.InvariantInfo));
                        break;

                    case 'i':
                        // Minutes with leading zeros - 00 to 59
                        result.Append(local.ToString("mm", DateTimeFormatInfo.InvariantInfo));
                        break;

                    case 'I':
                        // Whether or not the date is in daylights savings time - 1 if Daylight Savings Time, 0 otherwise.
                        result.Append(zone.IsDaylightSavingTime(local) ? "1" : "0");
                        break;

                    case 'j':
                        // Day of the month without leading zeros - 1 to 31
                        result.Append(local.ToString("%d", DateTimeFormatInfo.InvariantInfo));
                        break;

                    case 'l':
                        // A full textual representation of the day of the week - Sunday through Saturday
                        result.Append(local.ToString("dddd", DateTimeFormatInfo.InvariantInfo));
                        break;

                    case 'L':
                        // Whether it's a leap year - 1 if it is a leap year, 0 otherwise.
                        result.Append(DateTime.IsLeapYear(local.Year) ? "1" : "0");
                        break;

                    case 'm':
                        // Numeric representation of a month, with leading zeros - 01 through 12
                        result.Append(local.ToString("MM", DateTimeFormatInfo.InvariantInfo));
                        break;

                    case 'M':
                        // A short textual representation of a month, three letters - Jan through Dec
                        result.Append(local.ToString("MMM", DateTimeFormatInfo.InvariantInfo));
                        break;

                    case 'n':
                        // Numeric representation of a month, without leading zeros - 1 through 12
                        result.Append(local.ToString("%M", DateTimeFormatInfo.InvariantInfo));
                        break;

                    case 'N':
                        // ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0)
                        int day_of_week = (int)local.DayOfWeek;
                        result.Append(day_of_week == 0 ? 7 : day_of_week);
                        break;

                    case 'o':
                        {
                            // ISO-8601 year number. This has the same value as Y, except that if the ISO
                            // week number (W) belongs to the previous or next year, that year is used instead.
                            // (added in PHP 5.1.0)
                            int week, year;
                            GetIsoWeekAndYear(local, out week, out year);
                            result.Append(year);
                            break;
                        }

                    case 'O':
                        {
                            // Difference to Greenwich time (GMT) in hours Example: +0200
                            TimeSpan offset = zone.GetUtcOffset(local);
                            string sign = (offset.Ticks < 0) ? ((offset.Hours < 0) ? string.Empty : "-") : "+";
                            result.AppendFormat("{0}{1:00}{2:00}", sign, offset.Hours, offset.Minutes);
                            break;
                        }

                    case 'P':
                        {
                            // same as 'O' but with the extra colon between hours and minutes
                            // Difference to Greenwich time (GMT) in hours Example: +02:00
                            TimeSpan offset = zone.GetUtcOffset(local);
                            string sign = (offset.Ticks < 0) ? ((offset.Hours < 0) ? string.Empty : "-") : "+";
                            result.AppendFormat("{0}{1:00}:{2:00}", sign, offset.Hours, offset.Minutes);
                            break;
                        }

                    case 'r':
                        // RFC 822 formatted date Example: Thu, 21 Dec 2000 16:01:07 +0200
                        result.Append(local.ToString("ddd, dd MMM yyyy H:mm:ss ", DateTimeFormatInfo.InvariantInfo));
                        goto case 'O';

                    case 's':
                        // Seconds, with leading zeros - 00 through 59
                        result.Append(local.ToString("ss", DateTimeFormatInfo.InvariantInfo));
                        break;

                    case 'S':
                        result.Append(GetDayNumberSuffix(local.Day));
                        break;

                    case 't':
                        // Number of days in the given month 28 through 31
                        result.Append(DateTime.DaysInMonth(local.Year, local.Month));
                        break;

                    case 'T':
                        // Timezone setting of this machine Examples: EST, MDT ...
                        result.Append(zone.IsDaylightSavingTime(local) ? zone.DaylightName : zone.StandardName);
                        break;

                    case 'U':
                        // Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
                        result.Append(DateTimeUtils.UtcToUnixTimeStamp(utc));
                        break;

                    case 'u':
                        // Microseconds (added in PHP 5.2.2)
                        result.Append((utc.Millisecond / 1000).ToString("D6"));
                        break;

                    case 'w':
                        // Numeric representation of the day of the week - 0 (for Sunday) through 6 (for Saturday)
                        result.Append((int)local.DayOfWeek);
                        break;

                    case 'W':
                        {
                            // ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0) Example: 42 (the 42nd week in the year)
                            int week, year;
                            GetIsoWeekAndYear(local, out week, out year);
                            result.Append(week);
                            break;
                        }

                    case 'y':
                        // A two digit representation of a year Examples: 99 or 03
                        result.Append(local.ToString("yy", DateTimeFormatInfo.InvariantInfo));
                        break;

                    case 'Y':
                        // A full numeric representation of a year, 4 digits Examples: 1999 or 2003
                        result.Append(local.ToString("yyyy", DateTimeFormatInfo.InvariantInfo));
                        break;

                    case 'z':
                        // The day of the year starting from 0
                        result.Append(local.DayOfYear - 1);
                        break;

                    case 'Z':
                        // TimeZone offset in seconds:
                        result.Append((int)zone.GetUtcOffset(local).TotalSeconds);
                        break;

                    case '\\':
                        // Escape char. Output next character directly to the result.
                        escape = true;
                        break;

                    default:
                        // unrecognized character, print it as-is.
                        result.Append(ch);
                        break;
                }
            }

            if (escape)
                result.Append('\\');

            return result.ToString();
		public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone) 
		{
			if (destinationTimeZone == null) 
				throw new ArgumentNullException("destinationTimeZone");

			var utcDateTime = dateTimeOffset.UtcDateTime;

			bool isDst;
			var utcOffset =  destinationTimeZone.GetUtcOffset(utcDateTime, out isDst);

			return new DateTimeOffset(DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified) + utcOffset, utcOffset);
		}
Esempio n. 21
0
            /*
             * Compile:
             *    mcs /debug+ /out:tzi.exe /unsafe "/d:INSIDE_CORLIB;MONODROID;NET_4_0;LIBC;SELF_TEST" ../corlib/System/AndroidPlatform.cs System/TimeZone*.cs ../../build/common/Consts.cs ../Mono.Options/Mono.Options/Options.cs
             * Prep:
             *    mkdir -p android/tzdb/usr/share/zoneinfo
             *    mkdir -p android/tzdb/misc/zoneinfo/zoneinfo
             *    android_root=`adb shell echo '$ANDROID_ROOT' | tr -d "\r"`
             *    android_data=`adb shell echo '$ANDROID_DATA' | tr -d "\r"`
             *    adb pull $android_root/usr/share/zoneinfo   android/tzdb/usr/share/zoneinfo
             *    adb pull $android_data/misc/zoneinfo/tzdata android/tzdb/misc/zoneinfo
             * Run:
             *    # Dump all timezone names
             *    __XA_OVERRIDE_TIMEZONE_ID__=America/New_York ANDROID_ROOT=`pwd` ANDROID_DATA=`pwd` mono --debug tzi.exe --offset=1969-01-01
             *
             *    # Dump TimeZone data to files under path `tzdata`
             *    __XA_OVERRIDE_TIMEZONE_ID__=America/New_York ANDROID_ROOT=`pwd` ANDROID_DATA=`pwd` mono --debug tzi.exe -o android/tzdata
             *
             *    # Dump TimeZone rules for specific timezone data (as dumped above)
             *    mono tzi.exe --offset=2012-10-24 -i=tzdata/Asia/Amman
             */
            static void Main(string[] args)
            {
                DateTime?offset             = null;
                Func <IAndroidTimeZoneDB> c = () => GetDefaultTimeZoneDB();
                bool dump_rules             = false;

                Mono.Options.OptionSet p = null;
                p = new Mono.Options.OptionSet()
                {
                    { "i=",
                      "TimeZone data {FILE} to parse and dump",
                      v => DumpTimeZoneFile(v, offset) },
                    { "o=",
                      "Write TimeZone data files to {PATH}",
                      v => TimeZoneInfo.TimeZoneDataExportPath = v },
                    { "T=", "Create AndroidTzData from {PATH}.", v => {
                          c = () => new AndroidTzData(v);
                      } },
                    { "Z=", "Create ZoneInfoDB from {DIR}.", v => {
                          c = () => new ZoneInfoDB(v);
                      } },
                    { "offset=", "Show timezone info offset for DateTime {OFFSET}.", v => {
                          offset = DateTime.Parse(v);
                          Console.WriteLine("Using DateTime Offset: {0}", offset);
                      } },
                    { "R|dump-rules",
                      "Show timezone info offset for DateTime {OFFSET}.",
                      v => dump_rules = v != null },
                    { "help", "Show this message and exit", v => {
                          p.WriteOptionDescriptions(Console.Out);
                          Environment.Exit(0);
                      } },
                };
                p.Parse(args);
                AndroidTimeZones.db = c();
                Console.WriteLine("DB type: {0}", AndroidTimeZones.db.GetType().FullName);
                foreach (var id in GetAvailableIds())
                {
                    Console.Write("name={0,-40}", id);
                    try {
                        TimeZoneInfo zone = _GetTimeZone(id, id);
                        if (zone != null)
                        {
                            Console.Write(" {0,-40}", zone);
                            if (offset.HasValue)
                            {
                                Console.Write("From Offset: {0}", zone.GetUtcOffset(offset.Value));
                            }
                            if (dump_rules)
                            {
                                WriteZoneRules(zone);
                            }
                        }
                        else
                        {
                            Console.Write(" ERROR:null");
                        }
                    } catch (Exception e) {
                        Console.WriteLine();
                        Console.Write("ERROR: {0}", e);
                    }
                    Console.WriteLine();
                }
            }
Esempio n. 22
0
        public static string Format(DateTime utcDate, TimeZoneInfo timeZone, string format, double legacyOffset)
        {
            if (timeZone != null)
            {
                Double timeOffset = timeZone.GetUtcOffset(utcDate).TotalHours;
                try
                {
                    return utcDate.AddHours(timeOffset).ToString(format);
                }
                catch (ArgumentOutOfRangeException)  {  }

                //return TimeZoneInfo.ConvertTimeFromUtc(DateTime.SpecifyKind(utcDate, DateTimeKind.Utc), timeZone).ToString(format);

            }

            try
            {
                return utcDate.AddHours(legacyOffset).ToString(format);
            }
            catch (ArgumentOutOfRangeException) { }

            return utcDate.ToString(format);
        }
Esempio n. 23
0
        private void ValidateZoneEquality(Instant instant, DateTimeZone nodaZone, TimeZoneInfo windowsZone)
        {
            // The BCL is basically broken (up to and including .NET 4.5.1 at least) around its interpretation
            // of its own data around the new year. See http://codeblog.jonskeet.uk/2014/09/30/the-mysteries-of-bcl-time-zone-data/
            // for details. We're not trying to emulate this behaviour.
            // It's a lot *better* for .NET 4.6, 
            var utc = instant.InUtc();
            if ((utc.Month == 12 && utc.Day == 31) || (utc.Month == 1 && utc.Day == 1))
            {
                return;
            }

            var interval = nodaZone.GetZoneInterval(instant);

            // Check that the zone interval really represents a transition. It could be a change in
            // wall offset, name, or the split between standard time and daylight savings for the interval.
            if (interval.RawStart != Instant.BeforeMinValue)
            {
                var previousInterval = nodaZone.GetZoneInterval(interval.Start - Duration.Epsilon);
                Assert.AreNotEqual(new {interval.WallOffset, interval.Name, interval.StandardOffset},
                    new {previousInterval.WallOffset, previousInterval.Name, previousInterval.StandardOffset},
                    "Non-transition from {0} to {1}", previousInterval, interval);
            }
            var nodaOffset = interval.WallOffset;
            var windowsOffset = windowsZone.GetUtcOffset(instant.ToDateTimeUtc());
            Assert.AreEqual(windowsOffset, nodaOffset.ToTimeSpan(), $"Incorrect offset at {instant} in interval {interval}");
            var bclDaylight = windowsZone.IsDaylightSavingTime(instant.ToDateTimeUtc());
            Assert.AreEqual(bclDaylight, interval.Savings != Offset.Zero,
                $"At {instant}, BCL IsDaylightSavingTime={bclDaylight}; Noda savings={interval.Savings}");
        }
Esempio n. 24
0
 ///	<summary>
 /// Construct a PersonIdent from simple data
 ///	</summary>
 ///	<param name="name"></param>
 ///	<param name="emailAddress"></param>
 ///	<param name="when">Local time stamp.</param>
 ///	<param name="tz">Time zone.</param>
 public PersonIdent(string name, string emailAddress, DateTime when, TimeZoneInfo tz)
     : this(name, emailAddress, when.ToMillisecondsSinceEpoch(), (int)tz.GetUtcOffset(when).TotalMinutes)
 {
 }
        public static string SetDate(DateTime value, TimeZoneInfo timeZone)
        {
            var timeZoneOffset = TimeSpan.Zero;
            var utcTime = DateTime.MinValue;

            if (value.Kind == DateTimeKind.Local)
            {
                value = TimeZoneInfo.ConvertTimeToUtc(new DateTime(value.Ticks, DateTimeKind.Unspecified), timeZone);
            }

            if (value.Kind == DateTimeKind.Utc)
            {
                utcTime = value; //Set UTC time
                timeZoneOffset = timeZone.GetUtcOffset(value);
            }

            utcTime = utcTime.Add(timeZoneOffset);

            var dateString = utcTime.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffff", CultureInfo.InvariantCulture);
            var offsetString = timeZoneOffset.Ticks == 0 ? "Z" : string.Format("{0}{1,2:00}:{2,2:00}", timeZoneOffset.Ticks > 0 ? "+" : "", timeZoneOffset.Hours, timeZoneOffset.Minutes);
            return dateString + offsetString;
        }
Esempio n. 26
0
 public static double GetUtcOffsetHours(DateTime localDateTime, TimeZoneInfo timeZone)
 {
     TimeSpan ts = timeZone.GetUtcOffset(localDateTime);
     return ts.TotalHours;
 }
		static DateTime ConvertTimeToUtc (DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfoOptions flags)
		{
			if ((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) {
				if (sourceTimeZone == null)
					throw new ArgumentNullException ("sourceTimeZone");

				if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
					throw new ArgumentException ("Kind property of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");

				if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
					throw new ArgumentException ("Kind property of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");

				if (sourceTimeZone.IsInvalidTime (dateTime))
					throw new ArgumentException ("dateTime parameter is an invalid time");
			}

			if (dateTime.Kind == DateTimeKind.Utc)
				return dateTime;

			bool isDst;
			var utcOffset = sourceTimeZone.GetUtcOffset (dateTime, out isDst);

			DateTime utcDateTime;
			if (!TryAddTicks (dateTime, -utcOffset.Ticks, out utcDateTime, DateTimeKind.Utc))
				return DateTime.SpecifyKind (DateTime.MinValue, DateTimeKind.Utc);

			return utcDateTime;
		}
Esempio n. 28
0
        public static TimeSpan GetUtcOffset(DateTime dateTime, TimeZoneInfo timeZoneInfo)
        {
            // Unlike the default behavior of TimeZoneInfo.GetUtcOffset, it is prefered to choose
            // the DAYLIGHT time when the input is ambiguous, because the daylight instance is the
            // FIRST instance, and time moves in a forward direction.

            TimeSpan offset = timeZoneInfo.IsAmbiguousTime(dateTime)
                ? timeZoneInfo.GetAmbiguousTimeOffsets(dateTime).Max()
                : timeZoneInfo.GetUtcOffset(dateTime);

            return offset;
        }
            internal BclAdjustmentRule(TimeZoneInfo zone, TimeZoneInfo.AdjustmentRule rule)
            {
                // With .NET 4.6, adjustment rules can have their own standard offsets, allowing
                // a much more reasonable set of time zone data. Unfortunately, this isn't directly
                // exposed, but we can detect it by just finding the UTC offset for an arbitrary
                // time within the rule - the start, in this case - and then take account of the
                // possibility of that being in daylight saving time. Fortunately, we only need
                // to do this during the setup.
                var ruleStandardOffset = zone.GetUtcOffset(rule.DateStart);
                if (zone.IsDaylightSavingTime(rule.DateStart))
                {
                    ruleStandardOffset -= rule.DaylightDelta;
                }
                StandardOffset = ruleStandardOffset.ToOffset();

                // Although the rule may have its own standard offset, the start/end is still determined
                // using the zone's standard offset.
                var zoneStandardOffset = zone.BaseUtcOffset.ToOffset();

                // Note: this extends back from DateTime.MinValue to start of time, even though the BCL can represent
                // as far back as 1AD. This is in the *spirit* of a rule which goes back that far.
                Start = rule.DateStart == DateTime.MinValue ? Instant.BeforeMinValue : rule.DateStart.ToLocalDateTime().WithOffset(zoneStandardOffset).ToInstant();
                // The end instant (exclusive) is the end of the given date, so we need to add a day.
                End = rule.DateEnd == MaxDate ? Instant.AfterMaxValue : rule.DateEnd.ToLocalDateTime().PlusDays(1).WithOffset(zoneStandardOffset).ToInstant();
                Savings = rule.DaylightDelta.ToOffset();

                // Some rules have DST start/end of "January 1st", to indicate that they're just in standard time. This is important
                // for rules which have a standard offset which is different to the standard offset of the zone itself.
                if (IsStandardOffsetOnlyRule(rule))
                {
                    PartialMap = PartialZoneIntervalMap.ForZoneInterval(zone.StandardName, Start, End, StandardOffset, Offset.Zero);
                }
                else
                {
                    var daylightRecurrence = new ZoneRecurrence(zone.DaylightName, Savings, ConvertTransition(rule.DaylightTransitionStart), int.MinValue, int.MaxValue);
                    var standardRecurrence = new ZoneRecurrence(zone.StandardName, Offset.Zero, ConvertTransition(rule.DaylightTransitionEnd), int.MinValue, int.MaxValue);
                    var recurringMap = new DaylightSavingsDateTimeZone("ignored", StandardOffset, standardRecurrence, daylightRecurrence);
                    PartialMap = new PartialZoneIntervalMap(Start, End, recurringMap);
                }
            }
Esempio n. 30
0
    private static DateTime convertGMTTimeToTimeZone(DateTime gmtTime_, TimeZoneInfo tz_)
    {
      var offset = tz_.GetUtcOffset(gmtTime_.Date);

      return gmtTime_.Add(offset);
    }
Esempio n. 31
0
		private static long GetDatePart(char format, DateTime utc, TimeZoneInfo/*!*/ zone)
		{
            DateTime local = TimeZoneInfo.ConvertTimeFromUtc(utc, zone);// zone.ToLocalTime(utc);

			switch (format)
			{
				case 'B':
					// Swatch Beat (Internet Time) - 000 through 999
					return GetSwatchBeat(utc);

				case 'd':
					// Day of the month
					return local.Day;

				case 'g':
				case 'h':
					// 12-hour format:
					return (local.Hour == 12) ? 12 : local.Hour % 12;

				case 'G':
				case 'H':
					// 24-hour format:
					return local.Hour;

				case 'i':
					return local.Minute;

				case 'I':
					return zone.IsDaylightSavingTime(local) ? 1 : 0;

				case 'j':
					goto case 'd';

				case 'L':
					return DateTime.IsLeapYear(local.Year) ? 1 : 0;

				case 'm':
					return local.Month;

				case 'n':
					goto case 'm';

				case 's':
					return local.Second;

				case 't':
					return DateTime.DaysInMonth(local.Year, local.Month);

				case 'U':
					return DateTimeUtils.UtcToUnixTimeStamp(utc);

				case 'w':
					// day of the week - 0 (for Sunday) through 6 (for Saturday)
					return (int)local.DayOfWeek;

				case 'W':
					{
						// ISO-8601 week number of year, weeks starting on Monday:
						int week, year;
						GetIsoWeekAndYear(local, out week, out year);
						return week;
					}

				case 'y':
					return local.Year % 100;

				case 'Y':
					return local.Year;

				case 'z':
					return local.DayOfYear - 1;

				case 'Z':
					return (int)zone.GetUtcOffset(local).TotalSeconds;

				default:
					PhpException.InvalidArgument("format");
					return 0;
			}
Esempio n. 32
0
    public static DateTime ConvertDateTime(DateTime vanillaDateTime_, TimeZoneInfo fromTZ_, TimeZoneInfo toTZ_)
    {
      var offset = toTZ_.GetUtcOffset(vanillaDateTime_) - fromTZ_.GetUtcOffset(vanillaDateTime_);

      return vanillaDateTime_.Add(offset);
    }
        /// <summary>
        /// In cases where we can't get a zone mapping, either because we haven't kept
        /// up to date with the standard names or because the system language isn't English,
        /// try to work out the TZDB mapping by the transitions within the next few years.
        /// We only do this for the PCL, where we can't ask a TimeZoneInfo for its ID. Unfortunately
        /// this means we may sometimes return a mapping for zones which shouldn't be mapped at all, but that's
        /// probably okay and we return null if we don't get a 70% hit rate anyway. We look at all
        /// transitions in all primary mappings for the next year.
        /// Heuristically, this seems to be good enough to get the right results in most cases.
        /// </summary>
        /// <remarks>This method is not PCL-only as we would like to test it frequently. It will
        /// never actually be called in the non-PCL release though.</remarks>
        /// <param name="zone">Zone to resolve in a best-effort fashion.</param>
        internal string GuessZoneIdByTransitionsUncached(TimeZoneInfo zone)
        {
            // Very rare use of the system clock! Windows time zone updates sometimes sacrifice past
            // accuracy for future accuracy, so let's use the current year's transitions.
            int thisYear = SystemClock.Instance.GetCurrentInstant().InUtc().Year;
            Instant startOfThisYear = Instant.FromUtc(thisYear, 1, 1, 0, 0);
            Instant startOfNextYear = Instant.FromUtc(thisYear + 1, 1, 1, 0, 0);
            var candidates = WindowsMapping.PrimaryMapping.Values.Select(ForId).ToList();
            // Would create a HashSet directly, but it appears not to be present on all versions of the PCL...
            var instants = candidates.SelectMany(z => z.GetZoneIntervals(startOfThisYear, startOfNextYear))
                                     .Select(zi => Instant.Max(zi.RawStart, startOfThisYear)) // Clamp to start of interval
                                     .Distinct()
                                     .ToList();

            int bestScore = -1;
            DateTimeZone bestZone = null;
            foreach (var candidate in candidates)
            {
                int score = instants.Count(instant => Offset.FromTimeSpan(zone.GetUtcOffset(instant.ToDateTimeUtc())) == candidate.GetUtcOffset(instant));
                if (score > bestScore)
                {
                    bestScore = score;
                    bestZone = candidate;
                }
            }
            // If we haven't hit at least 70%, it's effectively unmappable
            return bestScore * 100 / instants.Count > 70 ? bestZone.Id : null;
        }
Esempio n. 34
0
 public static DateTime ToLocal(this DateTime utcValue, TimeZoneInfo timeZone)
 {
     return(new DateTime(utcValue.Ticks, DateTimeKind.Local).Add(timeZone.GetUtcOffset(utcValue)));
 }