public bool isPast(DateTime input)
        {
            var now         = DateTime.UtcNow;
            var instant     = Instant.FromDateTimeUtc(now);
            var unixTimeNow = instant.ToUnixTimeMilliseconds();

            var dateInput     = new DateTime(input.Year, input.Month, input.Day, 0, 0, 0);
            var instantInput  = Instant.FromDateTimeUtc(dateInput.ToUniversalTime());
            var unixTimeInput = instantInput.ToUnixTimeMilliseconds();

            return(unixTimeInput < unixTimeNow ? true : false);
        }
 public static DateTimeOffset TransformValue(DateTimeOffset value, string timeZoneName)
 {
     if (value > DateTimeOffset.MinValue)
     {
         var zoneProvider = DateTimeZoneProviders.Tzdb[timeZoneName];
         var zoneDateTime = Instant.FromDateTimeUtc(value.UtcDateTime)
                            .InZone(zoneProvider)
                            .ToDateTimeUnspecified();
         return(zoneDateTime);
     }
     return(value);
 }
Esempio n. 3
0
        internal IEntity ConvertToEntity(IEntityDefinition entityDefinition, Document doc)
        {
            var propertyBag = HiveJsonSerializer.Instance.Deserialize <PropertyBag>(doc.ToString());

            propertyBag[MetaConstants.IdProperty] =
                (propertyBag[MetaConstants.IdProperty] as string)?.Substring(entityDefinition.FullName.Length + 1);
            var entity = _entityFactory.Hydrate(entityDefinition, propertyBag);

            entity.Etag         = doc.ETag;
            entity.LastModified = Instant.FromDateTimeUtc(doc.Timestamp);
            return(entity);
        }
Esempio n. 4
0
        public void Should_replace_timestamp_information_from_event()
        {
            var now = DateTime.UtcNow;

            var envelope = new EnrichedContentEvent {
                Timestamp = Instant.FromDateTimeUtc(now)
            };

            var result = sut.Format("Date: $TIMESTAMP_DATE, Full: $TIMESTAMP_DATETIME", envelope);

            Assert.Equal($"Date: {now:yyyy-MM-dd}, Full: {now:yyyy-MM-dd-hh-mm-ss}", result);
        }
Esempio n. 5
0
        public IAsyncEnumerable <Request> QueryAllAsync(string key, DateTime fromDate, DateTime toDate,
                                                        CancellationToken ct = default)
        {
            Guard.NotNullOrEmpty(key);

            var timestampStart = Instant.FromDateTimeUtc(fromDate);
            var timestampEnd   = Instant.FromDateTimeUtc(toDate.AddDays(1));

            var find = Collection.Find(x => x.Key == key && x.Timestamp >= timestampStart && x.Timestamp < timestampEnd);

            return(find.ToAsyncEnumerable(ct).Select(x => x.ToRequest()));
        }
Esempio n. 6
0
 protected override Instant Cast(object value)
 {
     if (value is DateTimeOffset dateTimeOffset)
     {
         return(Instant.FromDateTimeOffset(dateTimeOffset));
     }
     if (value is DateTime dateTime)
     {
         return(Instant.FromDateTimeUtc(dateTime));
     }
     return(base.Cast(value));
 }
Esempio n. 7
0
        /// <summary>
        /// Method to determine if the current date selected is past or not
        /// </summary>
        public bool isPast()
        {
            var now         = DateTime.UtcNow;
            var instant     = Instant.FromDateTimeUtc(now);
            var unixTimeNow = instant.ToUnixTimeMilliseconds();

            var dateInput       = new DateTime(AppointmentDate.Year, AppointmentDate.Month, AppointmentDate.Day, 0, 0, 0);
            var instantInput    = Instant.FromDateTimeUtc(dateInput.ToUniversalTime());
            var currentUnixTime = instantInput.ToUnixTimeMilliseconds();

            return(currentUnixTime < unixTimeNow ? true : false);
        }
        /// <summary>
        /// Creates schemas container.
        /// </summary>
        /// <returns>Initialized <see cref="Schema"/> instance.</returns>
        public Schemas CreateSchemas()
        {
            IDateTimeZoneProvider dateTimeZoneProvider = _settings.DateTimeZoneProvider ?? DateTimeZoneProviders.Tzdb;
            var dateTimeZone  = dateTimeZoneProvider.GetSystemDefault();
            var instant       = Instant.FromDateTimeUtc(DateTime.UtcNow);
            var zonedDateTime = instant.InZone(dateTimeZone);
            var interval      = new Interval(instant,
                                             instant.PlusTicks(TimeSpan.TicksPerDay)
                                             .PlusTicks(TimeSpan.TicksPerHour)
                                             .PlusTicks(TimeSpan.TicksPerMinute)
                                             .PlusTicks(TimeSpan.TicksPerSecond)
                                             .PlusTicks(TimeSpan.TicksPerMillisecond));
            var    dateInterval = new DateInterval(zonedDateTime.Date, zonedDateTime.Date.PlusDays(1));
            Period period       = Period.Between(zonedDateTime.LocalDateTime, interval.End.InZone(dateTimeZone).LocalDateTime, PeriodUnits.AllUnits);
            var    offsetDate   = new OffsetDate(zonedDateTime.Date, zonedDateTime.Offset);
            var    offsetTime   = new OffsetTime(zonedDateTime.TimeOfDay, zonedDateTime.Offset);

            // https://xml2rfc.tools.ietf.org/public/rfc/html/rfc3339.html#anchor14
            return(new Schemas
            {
                Instant = () => StringSchema(instant, "date-time"),
                LocalDate = () => StringSchema(zonedDateTime.Date, "full-date"),
                LocalTime = () => StringSchema(zonedDateTime.TimeOfDay, "partial-time"),
                LocalDateTime = () => StringSchema(zonedDateTime.LocalDateTime),
                OffsetDateTime = () => StringSchema(instant.WithOffset(zonedDateTime.Offset), "date-time"),
                ZonedDateTime = () => StringSchema(zonedDateTime),
                Interval = () => new OpenApiSchema
                {
                    Type = "object",
                    Properties = new Dictionary <string, OpenApiSchema>
                    {
                        { ResolvePropertyName(nameof(Interval.Start)), StringSchema(interval.Start, "date-time") },
                        { ResolvePropertyName(nameof(Interval.End)), StringSchema(interval.End, "date-time") },
                    },
                },
                DateInterval = () => new OpenApiSchema
                {
                    Type = "object",
                    Properties = new Dictionary <string, OpenApiSchema>
                    {
                        { ResolvePropertyName(nameof(DateInterval.Start)), StringSchema(dateInterval.Start, "full-date") },
                        { ResolvePropertyName(nameof(DateInterval.End)), StringSchema(dateInterval.End, "full-date") },
                    },
                },
                Offset = () => StringSchema(zonedDateTime.Offset, "time-numoffset"),
                Period = () => StringSchema(period),
                Duration = () => StringSchema(interval.Duration),
                OffsetDate = () => StringSchema(offsetDate),
                OffsetTime = () => StringSchema(offsetTime),
                DateTimeZone = () => StringSchema(dateTimeZone),
            });
        }
Esempio n. 9
0
        public async Task <DataFileSystem> ExportSystem(PKSystem system)
        {
            await using var conn = await _db.Obtain();

            // Export members
            var members   = new List <DataFileMember>();
            var pkMembers = _repo.GetSystemMembers(conn, system.Id); // Read all members in the system

            await foreach (var member in pkMembers.Select(m => new DataFileMember
            {
                Id = m.Hid,
                Name = m.Name,
                DisplayName = m.DisplayName,
                Description = m.Description,
                Birthday = m.Birthday?.FormatExport(),
                Pronouns = m.Pronouns,
                Color = m.Color,
                AvatarUrl = m.AvatarUrl,
                ProxyTags = m.ProxyTags,
                KeepProxy = m.KeepProxy,
                Created = m.Created.FormatExport(),
                MessageCount = m.MessageCount
            }))
            {
                members.Add(member);
            }

            // Export switches
            var switches   = new List <DataFileSwitch>();
            var switchList = await _repo.GetPeriodFronters(conn, system.Id, Instant.FromDateTimeUtc(DateTime.MinValue.ToUniversalTime()), SystemClock.Instance.GetCurrentInstant());

            switches.AddRange(switchList.Select(x => new DataFileSwitch
            {
                Timestamp = x.TimespanStart.FormatExport(),
                Members   = x.Members.Select(m => m.Hid).ToList() // Look up member's HID using the member export from above
            }));

            return(new DataFileSystem
            {
                Version = 1,
                Id = system.Hid,
                Name = system.Name,
                Description = system.Description,
                Tag = system.Tag,
                AvatarUrl = system.AvatarUrl,
                TimeZone = system.UiTz,
                Members = members,
                Switches = switches,
                Created = system.Created.FormatExport(),
                LinkedAccounts = (await _repo.GetSystemAccounts(conn, system.Id)).ToList()
            });
        }
Esempio n. 10
0
    public void MapsTo_DateTime()
    {
        var mapper = Config.CreateMapper();

        var foo = new Foo3
        {
            Bar = DateTime.UtcNow
        };

        var result = mapper.Map <Foo1>(foo).Bar;

        result.Should().Be(Instant.FromDateTimeUtc(foo.Bar));
    }
Esempio n. 11
0
        public void ConvertUtcToLocalTime_ValidZoneId_ReturnCorrectLocalTime()
        {
            const string zoneId   = "Asia/Bangkok";
            var          timeZone = DateTimeZoneProviders.Tzdb[zoneId];

            var utcTime   = new DateTime(2021, 1, 1, 7, 30, 0, DateTimeKind.Utc);
            var instant   = Instant.FromDateTimeUtc(utcTime);
            var localTime = instant.InZone(timeZone).ToDateTimeUnspecified();

            var expectedLocalTime = new DateTime(2021, 1, 1, 14, 30, 0); // Bangkok offset is UTC+7

            Assert.Equal(expectedLocalTime, localTime);
        }
Esempio n. 12
0
        public static string FormatDateTimeWithOffset(DateTime dt, DateTimeZone dateTimeZone)
        {
            var fromDateTimeUtc   = Instant.FromDateTimeUtc(dt);
            var timeSpan          = dateTimeZone.GetUtcOffset(fromDateTimeUtc).ToTimeSpan();
            var localTime         = fromDateTimeUtc.InZone(dateTimeZone).LocalDateTime;
            var formattedDateTime = localTime.ToString("yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture);
            var sign       = Math.Sign(timeSpan.Hours);
            var signSymbol = sign >= 0
                ? "+"
                : "-";

            return($"{formattedDateTime}{signSymbol}{timeSpan.Hours:D2}:{timeSpan.Minutes:D2}");
        }
 private void CreateMappingsForInstantConvertor()
 {
     CreateMap <DateTime, Instant>().ConvertUsing(
         source => Instant.FromDateTimeUtc(
             source.Kind == DateTimeKind.Unspecified ? DateTime.SpecifyKind(source, DateTimeKind.Utc) : source.ToUniversalTime()
             )
         );
     CreateMap <DateTime?, Instant?>().ConvertUsing(
         source => source.HasValue
             ? Instant.FromDateTimeUtc(
             source.Value.Kind == DateTimeKind.Unspecified ? DateTime.SpecifyKind(source.Value, DateTimeKind.Utc) : source.Value.ToUniversalTime()
             )
             : default
        public static Instant UtcDateTimeToInstant(DateTime utcDateTime)
        {
            if (utcDateTime == MinDateTimeUtc)
            {
                return(Instant.MinValue);
            }
            if (utcDateTime == MaxDateTimeUtc)
            {
                return(Instant.MaxValue);
            }

            return(Instant.FromDateTimeUtc(utcDateTime));
        }
        public void Can_convert_instant_to_datetime(int year, int month, int day, int hour, int minute, int second)
        {
            SqlMapper.ITypeHandler handler = CreateHandler();
            var              dateTime      = new DateTime(year, month, day, hour, minute, second, DateTimeKind.Utc);
            Instant          instant       = Instant.FromDateTimeUtc(dateTime);
            IDbDataParameter parameter     = CreateParameter();

            handler.SetValue(parameter, instant);

            Assert.Equal(DbType.DateTime2, parameter.DbType);
            Assert.Equal(dateTime, parameter.Value);
            Assert.Equal(DateTimeKind.Utc, dateTime.Kind);
        }
        public static DateTimeOffset ToZonedDateTimeOffSet(this DateTime dateTime, string timeZoneName)
        {
            if (dateTime == DateTime.MinValue)
            {
                return(dateTime);
            }

            var timeZone = DateTimeZoneProviders.Tzdb[timeZoneName];

            var instant = Instant.FromDateTimeUtc(DateTime.SpecifyKind(dateTime, DateTimeKind.Utc));

            return(instant.InZone(timeZone).ToDateTimeOffset());
        }
Esempio n. 17
0
        public void Init()
        {
            _fakeTenantSettingsRepository = new Mock <ITenantSettingsRepository>();
            _fakeFeatureManager           = new Mock <IFeatureManager>();
            _fakeClock = new Mock <IClock>();
            _fakeAuditEventRepository = new Mock <IAuditEventRepository>();

            _currentDateTime = DateTime.UtcNow;

            var instant = Instant.FromDateTimeUtc(_currentDateTime);

            _fakeClock.Setup(x => x.GetCurrentInstant()).Returns(instant);
        }
        public void InstantConverter_EquivalentToIsoDateTimeConverter()
        {
            var dateTime     = new DateTime(2012, 1, 2, 3, 4, 5, DateTimeKind.Utc);
            var instant      = Instant.FromDateTimeUtc(dateTime);
            var jsonDateTime = JsonSerializer.Serialize(dateTime);
            var jsonInstant  = JsonSerializer.Serialize(instant, new JsonSerializerOptions
            {
                Converters    = { NodaConverters.InstantConverter },
                WriteIndented = false
            });

            Assert.AreEqual(jsonDateTime, jsonInstant);
        }
Esempio n. 19
0
        public static DateTime UtcToLocal(this DateTime utcDateTime, string zoneId)
        {
            if (utcDateTime.Kind != DateTimeKind.Utc)
            {
                throw new ArgumentException(
                          $"{nameof(utcDateTime)} must have {nameof(utcDateTime.Kind)} == {DateTimeKind.Utc}");
            }

            Instant instant = Instant.FromDateTimeUtc(utcDateTime);
            var     tz      = DateTimeZoneProviders.Tzdb[zoneId];

            return(instant.InZone(tz).ToDateTimeUnspecified());
        }
Esempio n. 20
0
        public void ZonedDateTimeArrayTest()
        {
            Instant       inst = Instant.FromDateTimeUtc(DateTime.UtcNow);
            LocalDateTime ldt  = LocalDateTime.FromDateTime(DateTime.Now);

            ZonedDateTime[] zoned = new ZonedDateTime[]
            { new ZonedDateTime(inst, DateTimeZone.Utc),
              new ZonedDateTime(inst, DateTimeZone.Utc),
              new ZonedDateTime(inst, DateTimeZone.Utc),
              new ZonedDateTime(inst, DateTimeZone.Utc),
              new ZonedDateTime(inst, DateTimeZone.Utc) };
            Assert.Equal(TestTools.Convert(zoned), zoned);
        }
Esempio n. 21
0
        public async Task JourneyMode_Unknown_Support()
        {
            var departureDate = Instant.FromDateTimeUtc(DateTime.UtcNow).InUtc().Date.PlusMonths(1);

            var itineraries = await Scanner.QueryFlight(new FlightQuerySettings(
                                                            new FlightRequestSettings(
                                                                Location.FromString("SYD-sky"),
                                                                Location.FromString("JNGO-sky"),
                                                                departureDate, departureDate.PlusDays(5)),
                                                            new FlightResponseSettings()));

            Assert.AreNotEqual(0, itineraries.Count);
        }
Esempio n. 22
0
        public async Task Flights_Can_Be_Queried()
        {
            var departureDate = Instant.FromDateTimeUtc(DateTime.UtcNow).InUtc().Date.PlusMonths(1);

            var itineraries = await Scanner.QueryFlight(new FlightQuerySettings(
                                                            new FlightRequestSettings(
                                                                Location.FromString("LOND-sky"),
                                                                Location.FromString("NYCA-sky"),
                                                                departureDate, departureDate.PlusDays(5)),
                                                            new FlightResponseSettings()));

            Assert.AreNotEqual(0, itineraries.Count);
        }
Esempio n. 23
0
 public static List <Event> LoadAndParseFeed(FileInfo file)
 {
     using (var reader = file.OpenRead())
     {
         return(Calendar.Load(reader).Events.Select(e => new Event
         {
             UId = e.Uid,
             Attendees = e.Attendees.Select(a => a.Value.ToString()).ToList(),
             Start = e.Start == null ? default : Instant.FromDateTimeUtc(e.Start.Value.ToUniversalTime()),
                     End = e.End == null ? default : Instant.FromDateTimeUtc(e.End.Value.ToUniversalTime()),
                           Duration = e.Duration == null ? default : Duration.FromTimeSpan(e.Duration),
                                      Summary = e.Summary
         }).ToList());
Esempio n. 24
0
        private List <Rotations> GetElapsedRotations(Instant current)
        {
            var result = new List <Rotations>();

            result = _db.Rotations
                     .Include(r => r.RotationUsers).ThenInclude(ru => ru.User)
                     .Where(r => r.LastNotification == null ||
                            Instant.FromDateTimeUtc(DateTime.SpecifyKind(r.LastNotification.Value, DateTimeKind.Utc))
                            + Duration.FromHours(23) < current)
                     .ToList();

            return(result);
        }
Esempio n. 25
0
        /// <summary>
        /// Converts given time to Utz DateTime with DateTime.Kind as Unspecified
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static DateTime ToUserDateTime(this DateTime date)
        {
            if (string.IsNullOrEmpty(ianaTimeZone))
            {
                return(date);
            }
            var timeZoneInfo = DateTimeZoneProviders.Tzdb[ianaTimeZone];

            date = (date.Kind == DateTimeKind.Utc) ? date : date.ToUniversalTime();
            return(Instant.FromDateTimeUtc(date)
                   .InZone(timeZoneInfo)
                   .ToDateTimeUnspecified());
        }
Esempio n. 26
0
        /// <summary>
        /// Converts the DateTime from UTC to the Local equivalent.
        /// </summary>
        /// <param name="dateToParse">The UTC DateTime object to parse</param>
        /// <returns>A DateTime in a Local equivalent</returns>
        public DateTime UtcToLocalDateTime(DateTime dateToParse)
        {
            if (dateToParse.Kind != DateTimeKind.Utc)
            {
                dateToParse = DateTime.SpecifyKind(dateToParse, DateTimeKind.Utc);
            }
            var instant = Instant
                          .FromDateTimeUtc(dateToParse);

            return(instant
                   .InZone(_dateTimeZone)
                   .ToDateTimeUnspecified());
        }
Esempio n. 27
0
    public async Task <JObject> ExportSystem(PKSystem system)
    {
        await using var conn = await _db.Obtain();

        var o = new JObject();

        o.Add("version", 2);

        o.Merge(system.ToJson(LookupContext.ByOwner));

        var config = await _repo.GetSystemConfig(system.Id);

        o.Add("config", config.ToJson());

        o.Add("accounts", new JArray((await _repo.GetSystemAccounts(system.Id)).ToList()));
        o.Add("members",
              new JArray((await _repo.GetSystemMembers(system.Id).ToListAsync()).Select(m =>
                                                                                        m.ToJson(LookupContext.ByOwner))));

        var groups = await _repo.GetSystemGroups(system.Id).ToListAsync();

        var j_groups = groups.Select(x => x.ToJson(LookupContext.ByOwner, needsMembersArray: true)).ToList();

        if (groups.Count > 0)
        {
            var q = await _repo.GetGroupMemberInfo(groups.Select(x => x.Id));

            foreach (var row in q)
            {
                ((JArray)j_groups.Find(x => x.Value <string>("id") == row.Group)["members"]).Add(row.Member);
            }
        }

        o.Add("groups", new JArray(j_groups));

        var switches   = new JArray();
        var switchList = await _repo.GetPeriodFronters(conn, system.Id, null,
                                                       Instant.FromDateTimeUtc(DateTime.MinValue.ToUniversalTime()), SystemClock.Instance.GetCurrentInstant());

        foreach (var sw in switchList)
        {
            var s = new JObject();
            s.Add("timestamp", sw.TimespanStart.FormatExport());
            s.Add("members", new JArray(sw.Members.Select(m => m.Hid)));
            switches.Add(s);
        }

        o.Add("switches", switches);

        return(o);
    }
Esempio n. 28
0
        /// <summary>
        /// Converts a UTC dateTime to Local dateTime in the ianaTimeZone
        /// </summary>
        /// <param name="dateTimeUtc"></param>
        /// <param name="ianaTimeZoneName"></param>
        /// <returns></returns>
        public static DateTime?ToLocalDateTime(this DateTime dateTimeUtc, string ianaTimeZoneName)
        {
            dateTimeUtc = DateTime.SpecifyKind(dateTimeUtc, DateTimeKind.Utc);

            DateTimeZone timeZone = DateTimeZoneProviders.Tzdb.GetZoneOrNull(ianaTimeZoneName);

            if (timeZone != null)
            {
                Instant instant       = Instant.FromDateTimeUtc(dateTimeUtc);
                var     zonedDateTime = instant.InZone(timeZone);
                return(zonedDateTime.ToDateTimeUnspecified());
            }
            return(null);
        }
Esempio n. 29
0
        /// <summary>
        /// The to event time zone.
        /// </summary>
        /// <param name="utcDateTime">
        /// The utc date time.
        /// </param>
        /// <param name="isUTC">
        /// The is utc.
        /// </param>
        /// <returns>
        /// The <see cref="DateTime"/>.
        /// </returns>
        public static DateTime ToEventTimeZone(this DateTime utcDateTime, bool isUTC = true)
        {
            if (utcDateTime == DateTime.MinValue)
            {
                return(utcDateTime);
            }

            if (isUTC && utcDateTime.Kind == DateTimeKind.Utc)
            {
                return(Instant.FromDateTimeUtc(utcDateTime).InZone(EventTimeZone).ToDateTimeUnspecified());
            }

            return(Instant.FromDateTimeOffset(utcDateTime).InZone(EventTimeZone).ToDateTimeUnspecified());
        }
        /// <summary>
        /// Adds the days taking into account DST.
        /// </summary>
        /// <param name="targetUtc">The target UTC.</param>
        /// <param name="timeZone">The time zone.</param>
        /// <param name="numberOfDays">The number of days.</param>
        /// <returns></returns>
        private DateTime AddDays(DateTime targetUtc, string timeZone, int numberOfDays)
        {
            Instant instant = Instant.FromDateTimeUtc(targetUtc);

            DateTimeZone timeZoneInfo = DateTimeZoneProviders.Tzdb[timeZone];

            ZonedDateTime zoned = instant.InZone(timeZoneInfo);

            LocalDateTime updated = zoned.LocalDateTime.PlusDays(numberOfDays); // Adding a number of days

            ZonedDateTime updatedZoned = timeZoneInfo.AtLeniently(updated);

            return(updatedZoned.ToDateTimeUtc());
        }