Example #1
0
        public void TestTimeZone_ShortTimeFormat_CentralAfricaTime()
        {
            TimeZoneInfo timeZone = TZConvert.GetTimeZoneInfo("Africa/Gaborone");

            CultureInfo culture = new CultureInfo("en-US");

            var formatter = new NumberDateFormat(DateFormat.LONG, DateFormat.MEDIUM, culture) // Medium time = no time zone info, but contains seconds
            {
                TimeZone = timeZone
            };

            const long Oct_31_1871_Ticks = 590376582130000000L; // Oct 31, 1871 05:30:13 UTC

            DateTime dateToParse = TimeZoneInfo.ConvertTime(new DateTime(Oct_31_1871_Ticks, DateTimeKind.Utc), timeZone);

            // Get the difference since the Unix epoch in milliseconds.
            long dateAsLong = dateToParse.GetMillisecondsSinceUnixEpoch();

            string actual = formatter.Format(dateAsLong);

            Console.WriteLine("Output of formatter.Format():");
            Console.WriteLine($"\"{actual}\"");

            // Convert the parsed result back to a long
            long parsedLong = Convert.ToInt64(formatter.Parse(actual));

            // Make sure round trip results in the same number
            Assert.AreEqual(dateAsLong, parsedLong);
        }
        public void GetTimeZoneInfo_UK_Input()
        {
            const string input  = "Europe/London";
            var          result = TimeSpanConverter.GetTimeZoneInfo(input);

            result.Should().Be(TZConvert.GetTimeZoneInfo("GMT Standard Time"));
        }
Example #3
0
        public async Task <IActionResult> Index()
        {
            try
            {
                var userTimeZone = TZConvert.GetTimeZoneInfo(
                    User.GetUserGraphTimeZone());
                var startOfWeek = CalendarController.GetUtcStartOfWeekInTimeZone(
                    DateTime.Today, userTimeZone);

                var events = await GetUserWeekCalendar(startOfWeek);

                var model = new CalendarViewModel(startOfWeek, events);

                return(View(model));
            }
            catch (ServiceException ex)
            {
                if (ex.InnerException is MicrosoftIdentityWebChallengeUserException)
                {
                    throw ex;
                }

                return(View(new CalendarViewModel())
                       .WithError("Error getting calendar view", ex.Message));
            }
        }
Example #4
0
        public async Task AddAsync(Access access)
        {
            CultureInfo  ci         = new CultureInfo("en-US");
            TimeZoneInfo hrBrasilia = TZConvert.GetTimeZoneInfo("E. South America Standard Time");

            if (access.CodeDevice != 0)
            {
                access.Device = await _context.Device.FindAsync(access.CodeDevice);

                access.Device.User = await _context.User.FindAsync(access.Device.UserName);

                access.Device.User.Rule = await _context.Rule.FindAsync(access.Device.User.CodeRule);
            }
            if (access.CodeControl != 0)
            {
                access.Control = await _context.Control.FindAsync(access.CodeControl);
            }

            foreach (Access accessIn in await _context.Access.ToListAsync())
            {
                string firstKey  = accessIn.Device.FirstBlock + "" + accessIn.Device.SecondBlock + "" + accessIn.Device.ThirdBlock + "" + accessIn.Device.FourthBlock;
                string secondKey = access.Device.FirstBlock + "" + access.Device.SecondBlock + "" + access.Device.ThirdBlock + "" + access.Device.FourthBlock;
                if (firstKey != secondKey)
                {
                    await _context.Access.AddAsync(access);

                    AccessLog accessLog = new AccessLog {
                        CodeAccess = access.Code, CodeDevice = access.CodeDevice, LastAccess = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, hrBrasilia).ToString()
                    };
                    await _context.AccessLog.AddAsync(accessLog);
                }
            }
        }
Example #5
0
        public async Task <IActionResult> Create([Bind("Id,Created,Task,Detail,IsComplete,IsWorkingOn,StartWorking,Finished")] TodoItemViewModel todoItemVM)
        {
            TodoItem todoItem;

            todoItemVM.Created = TimeZoneInfo
                                 .ConvertTime(DateTime.UtcNow, TZConvert.GetTimeZoneInfo("New Zealand Standard Time"));;
            todoItem = new TodoItem
            {
                Id          = todoItemVM.Id,
                Created     = todoItemVM.Created,
                Task        = todoItemVM.Task,
                Detail      = todoItemVM.Detail,
                IsComplete  = false,
                IsWorkingOn = false,
            };

            if (ModelState.IsValid)
            {
                _context.Add(todoItem);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(todoItem));
        }
        // GET /Calendar
        // Displays a calendar view of the current week for
        // the logged-in user
        public async Task <IActionResult> Index()
        {
            try
            {
                // TZConvert handles either an IANA or Windows identifier
                // Graph can return either
                var userTimeZone = TZConvert.GetTimeZoneInfo(
                    User.GetUserGraphTimeZone());
                var startOfWeek = CalendarController.GetUtcStartOfWeekInTimeZone(
                    DateTime.Today, userTimeZone);

                var events = await GetUserWeekCalendar(startOfWeek);

                var model = new CalendarViewModel(startOfWeek, events);

                return(View(model));
            }
            catch (ServiceException ex)
            {
                if (ex.InnerException is MsalUiRequiredException)
                {
                    throw;
                }

                return(View(new CalendarViewModel())
                       .WithError("Error getting calendar view", ex.Message));
            }
        }
Example #7
0
        public async Task <IActionResult> Schedule(string moniker)
        {
            var favorites = await _repo.GetUserWithFavoriteTalksForEventAsync(User.Identity.Name, moniker);

            var slots = await _repo.GetTalksInSlotsAsync(moniker);

            var categories = slots.SelectMany(s => s.ToList())
                             .SelectMany(s => s.Talks)
                             .Select(t => t.Category)
                             .OrderBy(t => t)
                             .Distinct()
                             .ToList();

            DateTime pickedSlot = DateTime.MinValue;

            if (slots.Count() > 0)
            {
                var easternZone = TZConvert.GetTimeZoneInfo("Eastern Standard Time");
                var eventTime   = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, easternZone);

                if (eventTime.Date == this._theEvent.EventDate)
                {
                    pickedSlot = slots[0].First().Time;

                    foreach (var slot in slots)
                    {
                        if (slot.First().Time > eventTime)
                        {
                            pickedSlot = slot.First().Time;
                        }
                    }
                }
            }
            return(View(Tuple.Create(slots, favorites, pickedSlot, categories)));
        }
        public void ShouldHandleDstFallBackTransition_AndNotRunTwiceOnTheSameDay()
        {
            TimeZoneInfo tz = TZConvert.GetTimeZoneInfo("Pacific Standard Time");

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("trigger1", "group1")
                               .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(1, 30).InTimeZone(tz))
                               .ForJob("job1", "group1")
                               .Build();

            DateTimeOffset firstRun = new DateTimeOffset(2016, 11, 6, 1, 30, 0, TimeSpan.FromHours(-7));
            DateTimeOffset?fireTime = trigger.GetFireTimeAfter(firstRun);

            // It should not fire again at 1:30-8 on the same day, but should instead fire at 1:30-8 the following day.
            DateTimeOffset expectedTime = new DateTimeOffset(2016, 11, 7, 1, 30, 0, TimeSpan.FromHours(-8));

            // We should definitely have a value
            Assert.NotNull(fireTime);

            // fireTime always is in UTC, but DateTimeOffset comparison normalized to UTC anyway.
            // Conversion here is for clarity of interpreting errors if the test fails.
            DateTimeOffset convertedFireTime = TimeZoneInfo.ConvertTime(fireTime.Value, tz);

            Assert.AreEqual(expectedTime, convertedFireTime);
        }
        public void ShouldHandleDstSpringForwardTransition()
        {
            TimeZoneInfo tz = TZConvert.GetTimeZoneInfo("Pacific Standard Time");

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("trigger1", "group1")
                               .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(2, 30).InTimeZone(tz))
                               .ForJob("job1", "group1")
                               .Build();

            DateTimeOffset midnight = new DateTimeOffset(2016, 3, 13, 0, 0, 0, TimeSpan.FromHours(-8));
            DateTimeOffset?fireTime = trigger.GetFireTimeAfter(midnight);

            // It should fire at the equivalent valid local time.  2:30-8 does not exist, so it should run at 3:30-7.
            DateTimeOffset expectedTime = new DateTimeOffset(2016, 3, 13, 3, 30, 0, TimeSpan.FromHours(-7));

            // We should definitely have a value
            Assert.NotNull(fireTime);

            // fireTime always is in UTC, but DateTimeOffset comparison normalized to UTC anyway.
            // Conversion here is for clarity of interpreting errors if the test fails.
            DateTimeOffset convertedFireTime = TimeZoneInfo.ConvertTime(fireTime.Value, tz);

            Assert.AreEqual(expectedTime, convertedFireTime);
        }
Example #10
0
 public static MeetupVm ToVm(this Meetup meetup)
 {
     return(new MeetupVm
     {
         Id = meetup.ExportId,
         Name = meetup.Name,
         CommunityId = (Communities)Enum.Parse(typeof(Communities), meetup.Community.ExportId, true),
         FriendIds = meetup.Friends.Select(x => new FriendReference {
             FriendId = x.Friend.ExportId
         }).ToList(),
         VenueId = meetup.Venue.ExportId,
         Sessions = meetup.Sessions.Select(x =>
         {
             var timeZone = TZConvert.GetTimeZoneInfo(meetup.Community.TimeZone);
             return new SessionVm
             {
                 TalkId = x.Talk.ExportId,
                 StartTime = TimeZoneInfo.ConvertTimeFromUtc(x.StartTime, timeZone)
                             .ToString("yyyy-MM-ddTHH:mm:ss"),
                 EndTime = TimeZoneInfo.ConvertTimeFromUtc(x.EndTime, timeZone)
                           .ToString("yyyy-MM-ddTHH:mm:ss")
             };
         }).ToList()
     });
 }
Example #11
0
        public async Task <AccessResponse> AuthAsync(int code)
        {
            try
            {
                CultureInfo  ci         = new CultureInfo("en-US");
                TimeZoneInfo hrBrasilia = TZConvert.GetTimeZoneInfo("E. South America Standard Time");
                var          exist      = await _deviceRepository.FindByIdAsync(code);

                if (exist == null && code != 0)
                {
                    return(new AccessResponse($"Device {code} not found"));
                }

                Access access = await _accessRepository.AuthByDeviceAsync(exist.Code);

                access.AccessLogs = await _accessLogRepository.ListByAccessCodeAsync(access.Code);

                await _unitOfWork.CompleteAsync();

                return(new AccessResponse(access));
            }
            catch (Exception e)
            {
                return(new AccessResponse($"An error occurred when deleting the access: { e.Message }"));
            }
        }
Example #12
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (string.IsNullOrWhiteSpace(Format))
            {
                // Handle empty format
                // Default to
                Format = "g";
            }

            DateTime dateTime;

            try
            {
                // TZConvert handles either an IANA or Windows identifier
                // Graph can return either
                var userTimeZone = TZConvert.GetTimeZoneInfo(TimeZone);
                dateTime = TimeZoneInfo.ConvertTimeFromUtc(Value.GetValueOrDefault().UtcDateTime, userTimeZone);
            }
            catch (TimeZoneNotFoundException)
            {
                // If the time zone isn't found, just use
                dateTime = Value.GetValueOrDefault().UtcDateTime;
            }

            output.TagName = "span";
            output.Content.SetContent(dateTime.ToString(Format));
        }
Example #13
0
        private async Task <DateTime> getDateByZipCode(string getDateByZipCode)
        {
            var dateTimeNow = DateTime.Now;
            var zipCode     = _catCFDI_CodigoPostals.FirstOrDefault(p => p.c_CodigoPostal == getDateByZipCode);

            Dictionary <string, string> timeZones = new Dictionary <string, string>();

            timeZones.Add("Tiempo del Centro", "Central Standard Time (Mexico)");
            timeZones.Add("Tiempo del Pacífico", "Pacific Standard Time (Mexico)");
            timeZones.Add("Tiempo del Pacífico en Frontera", "Pacific Standard Time");
            timeZones.Add("Tiempo del Noroeste", "Mountain Standard Time (Mexico)");
            timeZones.Add("Tiempo del Pacífico Sonora", "Pacific Standard Time (Mexico)");
            timeZones.Add("Tiempo del Centro en Frontera", "Central Standard Time");
            timeZones.Add("Tiempo del Noroeste en Frontera", "Pacific Standard Time");
            timeZones.Add("Tiempo del Sureste", "Eastern Standard Time");

            timeZones.TryGetValue(zipCode.DescripcionHusoHorario, out string timeZone);
            TimeZoneInfo tzi    = TZConvert.GetTimeZoneInfo(timeZone);
            var          result = TimeZoneInfo.ConvertTime(dateTimeNow, tzi);

            //Fix por problemas de sincronización del PAC
            result = result.AddMinutes(-5);

            return(result);
        }
Example #14
0
        public void TestTimeZone_ShortTimeFormat()
        {
            TimeZoneInfo timeZone = TZConvert.GetTimeZoneInfo("Pacific Standard Time");

            CultureInfo culture = new CultureInfo("en-US");

            var formatter = new NumberDateFormat(DateFormat.LONG, DateFormat.SHORT, culture) // Short time = no time zone info
            {
                TimeZone = timeZone
            };

            // Convert from Unix epoch to time zone.
            DateTime dateToParse = TimeZoneInfo.ConvertTimeFromUtc(J2N.Time.UnixEpoch, timeZone);

            // Get the difference since the Unix epoch in milliseconds.
            long dateAsLong = dateToParse.GetMillisecondsSinceUnixEpoch();

            string actual = formatter.Format(dateAsLong);

            Console.WriteLine("Output of formatter.Format():");
            Console.WriteLine($"\"{actual}\"");


            // Convert the parsed result back to a long
            long parsedLong = Convert.ToInt64(formatter.Parse(actual));

            // Make sure round trip results in the same number
            Assert.AreEqual(dateAsLong, parsedLong);
        }
Example #15
0
 private void Configuration(IGlobalConfiguration globalConfiguration)
 {
     globalConfiguration
     .UseSqlServerStorage(JsonConfig.GetSection("HangfireSqlserverConnectionString").Get <string>(), new SqlServerStorageOptions
     {
         CommandBatchMaxTimeout       = TimeSpan.FromMinutes(5),
         SlidingInvisibilityTimeout   = TimeSpan.FromMinutes(5),
         QueuePollInterval            = TimeSpan.Zero,
         UseRecommendedIsolationLevel = true,
         UsePageLocksOnDequeue        = true,
         DisableGlobalLocks           = true
     })
     .UseTagsWithSql()
     .UseConsole(new ConsoleOptions()
     {
         BackgroundColor = "#000079"
     })
     .UseHangfireHttpJob(new HangfireHttpJobOptions
     {
         MailOption = new MailOption
         {
             Server   = JsonConfig.GetSection("HangfireMail:Server").Get <string>(),
             Port     = JsonConfig.GetSection("HangfireMail:Port").Get <int>(),
             UseSsl   = JsonConfig.GetSection("HangfireMail:UseSsl").Get <bool>(),
             User     = JsonConfig.GetSection("HangfireMail:User").Get <string>(),
             Password = JsonConfig.GetSection("HangfireMail:Password").Get <string>(),
         },
         DefaultRecurringQueueName     = JsonConfig.GetSection("DefaultRecurringQueueName").Get <string>(),
         DefaultBackGroundJobQueueName = "DEFAULT",
         RecurringJobTimeZone          = TZConvert.GetTimeZoneInfo("Asia/Shanghai"), //这里指定了添加周期性job时的时区
         // RecurringJobTimeZone = TimeZoneInfo.Local
         // CheckHttpResponseStatusCode = code => (int)code < 400   //===》(default)
     });
 }
        public void ShouldHandleDstFallBackTransition()
        {
            TimeZoneInfo tz = TZConvert.GetTimeZoneInfo("Pacific Standard Time");

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("trigger1", "group1")
                               .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(1, 30).InTimeZone(tz))
                               .ForJob("job1", "group1")
                               .Build();

            DateTimeOffset midnight = new DateTimeOffset(2016, 11, 6, 0, 0, 0, TimeSpan.FromHours(-7));
            DateTimeOffset?fireTime = trigger.GetFireTimeAfter(midnight);

            // It should fire at the first instance, which is 1:30-7 - the DAYLIGHT time, not the standard time.
            DateTimeOffset expectedTime = new DateTimeOffset(2016, 11, 6, 1, 30, 0, TimeSpan.FromHours(-7));

            // We should definitely have a value
            Assert.NotNull(fireTime);

            // fireTime always is in UTC, but DateTimeOffset comparison normalized to UTC anyway.
            // Conversion here is for clarity of interpreting errors if the test fails.
            DateTimeOffset convertedFireTime = TimeZoneInfo.ConvertTime(fireTime.Value, tz);

            Assert.AreEqual(expectedTime, convertedFireTime);
        }
Example #17
0
        public void ShouldSumNumbersWithTwoWindowsAndDSTTimezone()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                // This test illustrate problems with daylight savings
                //Some timezone have daylight savings time (DST) resulting in two days in year that have either 23 or 25 hours.
                //Kafka streams currently support only fixed period for the moment.
                TimeZoneInfo zoneWithDST = TZConvert.GetTimeZoneInfo("Europe/Paris");

                var inputRecords = new List <TestRecord <string, int> > {
                    new TestRecord <string, int>(null, 1, TimeZoneInfo.ConvertTime(new DateTime(2019, 3, 30, 1, 39, 0, DateTimeKind.Unspecified), zoneWithDST)),
                    new TestRecord <string, int>(null, 2, TimeZoneInfo.ConvertTime(new DateTime(2019, 3, 30, 3, 0, 0, DateTimeKind.Unspecified), zoneWithDST)),
                    new TestRecord <string, int>(null, 7, TimeZoneInfo.ConvertTime(new DateTime(2019, 3, 30, 3, 10, 0, DateTimeKind.Unspecified), zoneWithDST)),
                    new TestRecord <string, int>(null, 1, TimeZoneInfo.ConvertTime(new DateTime(2019, 3, 31, 1, 39, 0, DateTimeKind.Unspecified), zoneWithDST)),
                    new TestRecord <string, int>(null, 2, TimeZoneInfo.ConvertTime(new DateTime(2019, 3, 31, 3, 0, 0, DateTimeKind.Unspecified), zoneWithDST)),
                    new TestRecord <string, int>(null, 7, TimeZoneInfo.ConvertTime(new DateTime(2019, 3, 31, 3, 10, 0, DateTimeKind.Unspecified), zoneWithDST)),
                };

                var expected = new List <(Windowed <int>, int)>
                {
                    (ToWindowed(1, TimeZoneInfo.ConvertTime(new DateTime(2019, 3, 29, 18, 0, 0, DateTimeKind.Unspecified), zoneWithDST), TimeZoneInfo.ConvertTime(new DateTime(2019, 3, 30, 18, 0, 0, DateTimeKind.Unspecified), zoneWithDST)), 1),
                    (ToWindowed(1, TimeZoneInfo.ConvertTime(new DateTime(2019, 3, 29, 18, 0, 0, DateTimeKind.Unspecified), zoneWithDST), TimeZoneInfo.ConvertTime(new DateTime(2019, 3, 30, 18, 0, 0, DateTimeKind.Unspecified), zoneWithDST)), 3),
                    (ToWindowed(1, TimeZoneInfo.ConvertTime(new DateTime(2019, 3, 29, 18, 0, 0, DateTimeKind.Unspecified), zoneWithDST), TimeZoneInfo.ConvertTime(new DateTime(2019, 3, 30, 18, 0, 0, DateTimeKind.Unspecified), zoneWithDST)), 10),
                    (ToWindowed(1, TimeZoneInfo.ConvertTime(new DateTime(2019, 3, 30, 18, 0, 0, DateTimeKind.Unspecified), zoneWithDST), TimeZoneInfo.ConvertTime(new DateTime(2019, 3, 31, 19, 0, 0, DateTimeKind.Unspecified), zoneWithDST)), 1),
                    (ToWindowed(1, TimeZoneInfo.ConvertTime(new DateTime(2019, 3, 30, 18, 0, 0, DateTimeKind.Unspecified), zoneWithDST), TimeZoneInfo.ConvertTime(new DateTime(2019, 3, 31, 19, 0, 0, DateTimeKind.Unspecified), zoneWithDST)), 3),
                    (ToWindowed(1, TimeZoneInfo.ConvertTime(new DateTime(2019, 3, 30, 18, 0, 0, DateTimeKind.Unspecified), zoneWithDST), TimeZoneInfo.ConvertTime(new DateTime(2019, 3, 31, 19, 0, 0, DateTimeKind.Unspecified), zoneWithDST)), 10)
                };

                Verify(inputRecords, expected, zoneWithDST);
            }
        }
Example #18
0
        public void TestDate6()
        {
            DateTimeOffset date = DateTimeOffset.FromUnixTimeMilliseconds(1514700000000L);
            var            tz   = TZConvert.GetTimeZoneInfo("Central Standard Time");

            date = TimeZoneInfo.ConvertTime(date,
                                            tz);

            IsoValue f = new IsoValue(IsoType.DATE6, date.DateTime);

            Assert.Equal("171231", f.ToString());
            Assert.Equal("171231", IsoType.DATE6.Format(date));
            var parsed = new Date6ParseInfo().Parse(1, "171231".GetSignedBytes(), 0, null);

            Assert.Equal("171231", parsed.ToString());
            Assert.Equal(f.Value, parsed.Value);

            var buf = new sbyte[3];

            buf[0] = 0x17;
            buf[1] = 0x12;
            buf[2] = 0x31;
            var dt = new Date6ParseInfo();

            parsed = dt.ParseBinary(2, buf, 0, null);
            Assert.Equal("171231", parsed.ToString());
            Assert.Equal(f.Value, parsed.Value);
        }
        public async Task <IActionResult> Index()
        {
            try
            {
                var userTimeZone = TZConvert.GetTimeZoneInfo(
                    User.GetUserGraphTimeZone());
                var startOfWeekUtc = CalendarController.GetUtcStartOfWeekInTimeZone(
                    DateTime.Today, userTimeZone);

                var events = await GetUserWeekCalendar(startOfWeekUtc);

                // Convert UTC start of week to user's time zone for
                // proper display
                var startOfWeekInTz = TimeZoneInfo.ConvertTimeFromUtc(startOfWeekUtc, userTimeZone);
                var model           = new CalendarViewModel(startOfWeekInTz, events);

                return(View(model));
            }
            catch (ServiceException ex)
            {
                if (ex.InnerException is MicrosoftIdentityWebChallengeUserException)
                {
                    throw;
                }

                return(View(new CalendarViewModel())
                       .WithError("Error getting calendar view", ex.Message));
            }
        }
Example #20
0
        // </InitializeGraphClientSnippet>

        // <GetUserInfoSnippet>
        private async Task GetUserInfo()
        {
            // Get the logged on user's profile (/me)
            var user = await GraphClient.Me.Request()
                       .Select(u => new
            {
                u.DisplayName,
                u.Mail,
                u.MailboxSettings,
                u.UserPrincipalName
            })
                       .GetAsync();

            UserPhoto = ImageSource.FromStream(() => GetUserPhoto());
            UserName  = user.DisplayName;
            UserEmail = string.IsNullOrEmpty(user.Mail) ? user.UserPrincipalName : user.Mail;
            try
            {
                UserTimeZone = TZConvert.GetTimeZoneInfo(user.MailboxSettings.TimeZone);
            }
            catch
            {
                // Default to local time zone
                UserTimeZone = TimeZoneInfo.Local;
            }
        }
        /// <summary>
        /// Assumes Unspecified = Local.
        /// </summary>
        public static string LocalOrUtcToTimeZoneNoAbbreviation(this DateTime unspecifiedAsLocalOrLocalOrutcDateTime, string timeZoneId)
        {
            var istTZ         = TZConvert.GetTimeZoneInfo(timeZoneId);
            var convertedTime = TimeZoneInfo.ConvertTime(unspecifiedAsLocalOrLocalOrutcDateTime, istTZ);

            return(String.Format("{0}", convertedTime.ToShortDateString()));
        }
Example #22
0
        public DateTime GetReportLastCheck(HealthStatus status)
        {
            var behaviour = _healthCheck
                            .AlertBehaviour
                            .FirstOrDefault(b => b.TransportName == _alertTransportSettings.Name);

            if (behaviour == null)
            {
                return(DateTime.MinValue);
            }

            if (string.IsNullOrEmpty(behaviour.Timezone))
            {
                return(behaviour.LastCheck);
            }

            var timezone = TZConvert.GetTimeZoneInfo(behaviour.Timezone);

            if (timezone == null)
            {
                return(behaviour.LastCheck);
            }

            var convertedTime = TimeZoneInfo.ConvertTime(behaviour.LastCheck, timezone);

            return(convertedTime);
        }
Example #23
0
        public static List <TimeZoneInfo> GetWindowsTimeZoneInfos(bool ignoreTimeZoneNotFoundException = true)
        {
            var timezoneInfos = new List <TimeZoneInfo>();

            foreach (var windowsTimeZoneId in TZConvert.KnownWindowsTimeZoneIds)
            {
                try
                {
                    var timezoneInfo = TZConvert.GetTimeZoneInfo(windowsTimeZoneId);
                    timezoneInfos.Add(timezoneInfo);
                }
                catch (TimeZoneNotFoundException exception)
                {
                    if (ignoreTimeZoneNotFoundException)
                    {
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            return(timezoneInfos);
        }
        public OkResult Post([FromBody] string timeZoneId)
        {
            var utcTime       = DateTime.UtcNow;
            var requestedTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, TZConvert.GetTimeZoneInfo(timeZoneId));
            var ip            = this.HttpContext.Connection.RemoteIpAddress.ToString();

            var queriedTime = new CurrentTimeQuery
            {
                UTCTime    = utcTime,
                ClientIp   = ip,
                Time       = requestedTime,
                TimeZoneId = timeZoneId
            };

            _clockworkContext.CurrentTimeQueries.Add(queriedTime);
            var count = _clockworkContext.SaveChanges();

            Console.WriteLine("{0} records saved to database", count);

            Console.WriteLine();
            foreach (var CurrentTimeQuery in _clockworkContext.CurrentTimeQueries)
            {
                Console.WriteLine(" - {0}", CurrentTimeQuery.UTCTime);
            }

            return(Ok());
        }
Example #25
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            // this is a hack that should not be needed. Need to understand why 2.0.0 upgrade causes this to match head & body tags which causes layout exception
            // Exception = InvalidOperationException: RenderBody has not been called for the page at '/Views/Shared/_Layout.cshtml'. To ignore call IgnoreBody().
            if (output.TagName != "time")
            {
                return;
            }

            output.TagName = null;

            if (!Value.HasValue)
            {
                output.Content.SetContent("*");
            }
            else
            {
                var dateTimeToDisplay = Value.Value;
                if (!string.IsNullOrEmpty(TargetTimeZoneId))
                {
                    TimeZoneInfo targetTimeZone = TZConvert.GetTimeZoneInfo(TargetTimeZoneId);
                    var          targetOffset   = targetTimeZone.GetUtcOffset(dateTimeToDisplay);
                    dateTimeToDisplay = dateTimeToDisplay.ToOffset(targetOffset);
                }
                var formattedTime = dateTimeToDisplay.ToString(Format);
                output.Content.SetContent(formattedTime);
            }
        }
Example #26
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _log.LogInformation("Bills worker starting up.");
            _scheduler = await _schedulerFactory.GetScheduler(cancellationToken);

            await _scheduler.Start(cancellationToken);

            var job = JobBuilder.Create<BillsJob>()
                .WithIdentity("billsJob", "jobs")
                .Build();

            var trigger = TriggerBuilder.Create()
                .WithIdentity("billsJobTrigger", "jobs")
                .StartNow()
                .WithCronSchedule(_options.Value.CronSchedule, c =>
                {
                    if (_options.Value.CronTimeZone.IsNotEmpty())
                    {
                        c.InTimeZone(TZConvert.GetTimeZoneInfo(_options.Value.CronTimeZone));
                    }
                })
                .Build();

            await _scheduler.ScheduleJob(job, trigger, cancellationToken);
        }
Example #27
0
 public static IServiceCollection AddHangFireModule(this IServiceCollection service, IConfiguration configuration)
 {
     service.AddHangfire(x => x.UseSqlServerStorage(
                             configuration.GetSection("HangfireSqlserverConnectionString").Get <string>(),
                             new SqlServerStorageOptions()
     {
         CommandBatchMaxTimeout       = TimeSpan.FromMinutes(5),
         SlidingInvisibilityTimeout   = TimeSpan.FromMinutes(5),
         QueuePollInterval            = TimeSpan.Zero,
         UseRecommendedIsolationLevel = true,
         UsePageLocksOnDequeue        = true,
         DisableGlobalLocks           = true
     })
                         .UseTagsWithSql()
                         .UseConsole(new ConsoleOptions()
     {
         BackgroundColor = "#000079"
     })
                         .UseHangfireHttpJob(new HangfireHttpJobOptions
     {
         MailOption = new MailOption
         {
             Server   = configuration.GetSection("HangfireMail:Server").Get <string>(),
             Port     = configuration.GetSection("HangfireMail:Port").Get <int>(),
             UseSsl   = configuration.GetSection("HangfireMail:UseSsl").Get <bool>(),
             User     = configuration.GetSection("HangfireMail:User").Get <string>(),
             Password = configuration.GetSection("HangfireMail:Password").Get <string>()
         },
         DefaultRecurringQueueName     = configuration.GetSection("DefaultRecurringQueueName").Get <string>(),
         DefaultBackGroundJobQueueName = "DEFAULT",
         RecurringJobTimeZone          = TZConvert.GetTimeZoneInfo("Asia/Shanghai")
     }));
     return(service);
 }
Example #28
0
        public static DateTime ApplyTimeZoneOffset(this DateTime utc, string timeZone)
        {
            var timeZoneInfo   = TZConvert.GetTimeZoneInfo(timeZone);
            var offsetTimespan = timeZoneInfo.GetUtcOffset(utc);

            return(utc - offsetTimespan);
        }
Example #29
0
        private bool TryParseTimeZone(string timeZone, out TimeZoneInfo tzi)
        {
            tzi = null;
            if (!TZConvert.TryGetTimeZoneInfo(timeZone, out tzi))
            {
                foreach (string tz in TZConvert.KnownIanaTimeZoneNames)
                {
                    if (tz.ToLowerInvariant().Contains(timeZone.ToLowerInvariant()))
                    {
                        tzi = TZConvert.GetTimeZoneInfo(tz);
                        return(true);
                    }
                }

                foreach (string tz in TZConvert.KnownWindowsTimeZoneIds)
                {
                    if (tz.ToLowerInvariant().Contains(timeZone.ToLowerInvariant()))
                    {
                        tzi = TZConvert.GetTimeZoneInfo(tz);
                        return(true);
                    }
                }
                return(false);
            }

            return(true);
        }
Example #30
0
        public static DateTime GetCurrentSystemDateByTz(string timezone)
        {
            // Due to TimeZone problem per OS, we need to use another lib to exchange corresponding TZ
            var tz = TZConvert.GetTimeZoneInfo(timezone);

            return(TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tz));
        }