當前位置: 首頁>>代碼示例>>C#>>正文


C# System.TimeZoneInfo類代碼示例

本文整理匯總了C#中System.TimeZoneInfo的典型用法代碼示例。如果您正苦於以下問題:C# TimeZoneInfo類的具體用法?C# TimeZoneInfo怎麽用?C# TimeZoneInfo使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


TimeZoneInfo類屬於System命名空間,在下文中一共展示了TimeZoneInfo類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: RecurringJobSchedulerFacts

        public RecurringJobSchedulerFacts()
        {
            _storage = new Mock<JobStorage>();
            _client = new Mock<IBackgroundJobClient>();
            _instantFactory = new Mock<IScheduleInstantFactory>();
            _throttler = new Mock<IThrottler>();
            _token = new CancellationTokenSource().Token;

            // Setting up the successful path
            _instant = new Mock<IScheduleInstant>();
            _instant.Setup(x => x.GetNextInstants(It.IsAny<DateTime?>())).Returns(new[] { _instant.Object.NowInstant });

            _timeZone = TimeZoneInfo.Local;

            _instantFactory.Setup(x => x.GetInstant(It.IsNotNull<CrontabSchedule>(), It.IsNotNull<TimeZoneInfo>()))
                .Returns(() => _instant.Object);

            _recurringJob = new Dictionary<string, string>
            {
                { "Cron", "* * * * *" },
                { "Job", JobHelper.ToJson(InvocationData.Serialize(Job.FromExpression(() => Console.WriteLine()))) },
                { "TimeZoneId", _timeZone.Id }
            };

            _connection = new Mock<IStorageConnection>();
            _storage.Setup(x => x.GetConnection()).Returns(_connection.Object);

            _connection.Setup(x => x.GetAllItemsFromSet("recurring-jobs"))
                .Returns(new HashSet<string> { RecurringJobId });

            _connection.Setup(x => x.GetAllEntriesFromHash(String.Format("recurring-job:{0}", RecurringJobId)))
                .Returns(_recurringJob);

            _client.Setup(x => x.Create(It.IsAny<Job>(), It.IsAny<IState>())).Returns("job-id");
        }
開發者ID:djrineh,項目名稱:Hangfire,代碼行數:35,代碼來源:RecurringJobSchedulerFacts.cs

示例2: HomeController

 public HomeController()
 {
     DbInitializer.Initialize();
     profiler = MiniProfiler.Current;
     EasternStandardTimeId = "Eastern Standard Time";
     ESTTimeZone = TimeZoneInfo.FindSystemTimeZoneById(EasternStandardTimeId);
 }
開發者ID:mhsohail,項目名稱:eQuiz,代碼行數:7,代碼來源:HomeController.cs

示例3: DateTimeConverter

		static DateTimeConverter()
		{
			LocalZoneInfo = TimeZoneInfo.Local;
			CurrentZone = TimeZone.CurrentTimeZone;
			var offset = LocalZoneInfo.BaseUtcOffset;
			var sbWithout = new StringBuilder();
			if (offset.TotalSeconds >= 0)
				sbWithout.Append('+');
			sbWithout.Append(offset.Hours.ToString("00"));
			sbWithout.Append(':');
			sbWithout.Append(offset.Minutes.ToString("00"));
			//tough luck if you have seconds in timezone offset
			TimeZoneWithoutDaylightSaving = sbWithout.ToString();
			var rules = LocalZoneInfo.GetAdjustmentRules();
			if (rules.Length == 1 && rules[0].DateStart == DateTime.MinValue && rules[0].DateEnd == DateTime.MinValue)
			{
				var sbWith = new StringBuilder();
				var totalOffset = offset.Add(rules[0].DaylightDelta);
				if (totalOffset.TotalSeconds >= 0)
					sbWith.Append('+');
				sbWith.Append(totalOffset.Hours.ToString("00"));
				sbWith.Append(':');
				sbWith.Append(totalOffset.Minutes.ToString("00"));
				TimeZoneWithDaylightSaving = sbWith.ToString();
			}
		}
開發者ID:dstimac,項目名稱:revenj,代碼行數:26,代碼來源:DateTimeConverter.cs

示例4: CalculateStartTime

        /// <summary>
        /// Uses now as a basis to calculate the next scheduled date. 
        /// </summary>
        /// <param name="tzi">user's time zone</param>
        /// <param name="recurrence">pattern</param>
        /// <param name="timeOfDay">user's preferred time of day, in user's time zone</param>
        /// <param name="userTime">start time in user time zone</param>
        /// <param name="utc">start time in utc</param>
        /// <returns>false if not within start-end period, true otherwise</returns>
        public static bool CalculateStartTime(TimeZoneInfo tzi, string recurrence, TimeSpan timeOfDay, out DateTime userTime, out DateTime utc)
        {
            DateTime utcNow = DateTime.UtcNow;
            userTime = utc = DateTime.MinValue;

            TimeSpan? ts = ScheduledTask.FixedInterval(recurrence);
            if (ts.HasValue)
            {
                utc = utcNow + ts.Value;
                userTime = TimeZoneInfo.ConvertTimeFromUtc(utc, tzi);
            }
            else
            {
                DateTime userNow = TimeZoneInfo.ConvertTimeFromUtc(utcNow, tzi);

                DateTime runDate = userNow.Date;
                if (userNow.TimeOfDay > timeOfDay) runDate += TimeSpan.FromDays(1);

                DateTime dt;
                if (recurrence != null)
                {
                    DateGenerator gen = DateGeneratorFactory.Create(recurrence);
                    DateTime next = gen.OnOrAfter(runDate);
                    if (next == default(DateTime)) return false; // outside range
                    dt = next + timeOfDay;
                }
                else
                {
                    dt = runDate + timeOfDay;
                }
                userTime = dt;
                utc = TimeZoneInfo.ConvertTimeToUtc(dt, tzi);
            }
            return true;
        }
開發者ID:ashish-antil,項目名稱:Products,代碼行數:44,代碼來源:TaskManager.cs

示例5: GetGMTOffset

		/// <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;
		}
開發者ID:RickIsWright,項目名稱:nHapi,代碼行數:12,代碼來源:DataTypeUtil.cs

示例6: ScheduleInstant

        public ScheduleInstant(DateTime nowInstant, TimeZoneInfo timeZone, [NotNull] CrontabSchedule schedule)
        {
            if (schedule == null) throw new ArgumentNullException("schedule");
            if (nowInstant.Kind != DateTimeKind.Utc)
            {
                throw new ArgumentException("Only DateTime values in UTC should be passed.", "nowInstant");
            }

            _timeZone = timeZone;
            _schedule = schedule;

            NowInstant = nowInstant.AddSeconds(-nowInstant.Second);

            var nextOccurrences = _schedule.GetNextOccurrences(
                TimeZoneInfo.ConvertTime(NowInstant, TimeZoneInfo.Utc, _timeZone),
                DateTime.MaxValue);

            foreach (var nextOccurrence in nextOccurrences)
            {
                if (_timeZone.IsInvalidTime(nextOccurrence)) continue;

                NextInstant = TimeZoneInfo.ConvertTime(nextOccurrence, _timeZone, TimeZoneInfo.Utc);
                break;
            }
        }
開發者ID:GitHuang,項目名稱:Hangfire,代碼行數:25,代碼來源:ScheduleInstant.cs

示例7: GetLinkerTime

        /// <summary>
        /// 獲取程序集的鏈接時間
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="target"></param>
        /// <returns></returns>
        public static DateTime GetLinkerTime(Assembly assembly, TimeZoneInfo target = null)
        {
            var filePath = assembly.Location;
            const int c_PeHeaderOffset = 60;
            const int c_LinkerTimestampOffset = 8;

            var buffer = new byte[2048];

            using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                stream.Read(buffer, 0, 2048);

            var offset = BitConverter.ToInt32(buffer, c_PeHeaderOffset);
            var secondsSince1970 = BitConverter.ToInt32(buffer, offset + c_LinkerTimestampOffset);
            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            var linkTimeUtc = epoch.AddSeconds(secondsSince1970);

            var tz = target;
            try
            {
                if (tz == null)
                    tz = TimeZoneInfo.Local;
            }
            catch
            {
                tz = TimeZoneInfo.Utc;
            }
            var localTime = TimeZoneInfo.ConvertTimeFromUtc(linkTimeUtc, tz);

            return localTime;
        }
開發者ID:aaasoft,項目名稱:Quick.OwinMVC,代碼行數:37,代碼來源:AssemblyUtils.cs

示例8: ToTimeZone

        public static DateTime ToTimeZone(this DateTime utcTime, TimeZoneInfo timeZoneInfo)
        {
            if (timeZoneInfo == null)
                return utcTime.ToLocalTime();

            return TimeZoneInfo.ConvertTimeFromUtc(utcTime, timeZoneInfo);
        }
開發者ID:ukionik,項目名稱:StoreEngine,代碼行數:7,代碼來源:DateTimeExtensions.cs

示例9: PlaylistWindow

		public PlaylistWindow(uint channelNumber, string channelCaption, TimeZoneInfo timezone) {
			InitializeComponent();
			Title=channelCaption;
			this.channelNumber=channelNumber;
			this.timezone=timezone;
			this.Loaded+=Window_Loaded;
		}
開發者ID:drdax,項目名稱:Radio,代碼行數:7,代碼來源:PlaylistWindow.xaml.cs

示例10: ToUtc

        public static DateTime? ToUtc(this DateTime? dateTime, TimeZoneInfo timeZoneInfo)
        {
            if (!dateTime.HasValue)
                return null;

            return ToUtc(dateTime.Value, timeZoneInfo);
        }
開發者ID:ukionik,項目名稱:StoreEngine,代碼行數:7,代碼來源:DateTimeExtensions.cs

示例11: Dump

        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");
        }
開發者ID:nodatime,項目名稱:tzvalidate,代碼行數:35,代碼來源:Program.cs

示例12: DateTimeInUserZone

 public static DateTime? DateTimeInUserZone(DateTime dt, TimeZoneInfo userZone)
 {
     if (dt.Kind == DateTimeKind.Local) throw new ArgumentException("Invalid date kind (local");
     if (dt == default(DateTime)) return null; // we don't want to display 0001-01-01T00:00:00
     if (dt.Kind == DateTimeKind.Utc) dt = TimeZoneInfo.ConvertTimeFromUtc(dt, userZone);
     return dt;
 }
開發者ID:ashish-antil,項目名稱:Products,代碼行數:7,代碼來源:ImardaFormatProvider.cs

示例13: FirstViewController

 public FirstViewController(IntPtr handle)
     : base(handle)
 {
     this.Title = NSBundle.MainBundle.LocalizedString ("First", "First");
     this.TabBarItem.Image = UIImage.FromBundle ("first");
     this.selectedTimeZone = TimeZoneInfo.Local;
 }
開發者ID:vahidtaslimi,項目名稱:TimeZoneConvertor,代碼行數:7,代碼來源:FirstViewController.cs

示例14: FixTimeZoneDSTRRules

 public static void FixTimeZoneDSTRRules (TimeZoneInfo tz, ITimeZone iCalTz)
 {
   var adjustments = tz.GetAdjustmentRules();
   foreach (var tziItems in iCalTz.TimeZoneInfos)
   {
     var matchingAdj = adjustments.FirstOrDefault(a => (a.DateStart.Year == tziItems.Start.Year)) ?? adjustments.FirstOrDefault();
     if (matchingAdj != null)
     {
       if ((matchingAdj.DateEnd.Year != 9999) && !(tziItems.Name.Equals("STANDARD") && matchingAdj == adjustments.Last()))
       {
         tziItems.RecurrenceRules[0].Until =
           DateTime.SpecifyKind(matchingAdj.DateEnd.Date.AddDays(1).Subtract(tz.BaseUtcOffset), DateTimeKind.Utc);
       }
       if (tziItems.Name.Equals("STANDARD"))
       {
         if (!matchingAdj.DaylightTransitionEnd.IsFixedDateRule)
         {
           var startYear = tziItems.Start.Year;
           tziItems.Start = CalcTransitionStart(matchingAdj.DaylightTransitionEnd, startYear);
         }
       }
       else
       {
         if (!matchingAdj.DaylightTransitionStart.IsFixedDateRule)
         {
           var startYear = tziItems.Start.Year;
           tziItems.Start = CalcTransitionStart(matchingAdj.DaylightTransitionStart, startYear);
         }
       }
     }
   }
 }
開發者ID:aluxnimm,項目名稱:outlookcaldavsynchronizer,代碼行數:32,代碼來源:CalendarDataPreprocessor.cs

示例15: CalcTransitionStart

    private static iCalDateTime CalcTransitionStart(TimeZoneInfo.TransitionTime transition, int year)
    {
      // For non-fixed date rules, get local calendar
      Calendar cal = CultureInfo.CurrentCulture.Calendar;
      // Get first day of week for transition
      // For example, the 3rd week starts no earlier than the 15th of the month
      int startOfWeek = transition.Week * 7 - 6;
      // What day of the week does the month start on?
      int firstDayOfWeek = (int)cal.GetDayOfWeek(new DateTime(year, transition.Month, 1));
      // Determine how much start date has to be adjusted
      int transitionDay;
      int changeDayOfWeek = (int)transition.DayOfWeek;

      if (firstDayOfWeek <= changeDayOfWeek)
        transitionDay = startOfWeek + (changeDayOfWeek - firstDayOfWeek);
      else
        transitionDay = startOfWeek + (7 - firstDayOfWeek + changeDayOfWeek);

      // Adjust for months with no fifth week
      if (transitionDay > cal.GetDaysInMonth(year, transition.Month))
        transitionDay -= 7;

      return new iCalDateTime(new DateTime( year, transition.Month, transitionDay,
                                            transition.TimeOfDay.Hour, transition.TimeOfDay.Minute, transition.TimeOfDay.Second));
    }
開發者ID:aluxnimm,項目名稱:outlookcaldavsynchronizer,代碼行數:25,代碼來源:CalendarDataPreprocessor.cs


注:本文中的System.TimeZoneInfo類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。