当前位置: 首页>>代码示例>>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;未经允许,请勿转载。