示例#1
0
    public void ToCollection_TimeOnlyColumn(string dataSourceName, DataSourceType mode)
    {
        var dataSource = DataSource(dataSourceName, mode);

        try
        {
            var uniqueKey = Guid.NewGuid().ToString();
            var cust1     = new CustomerWithTime()
            {
                FullName = uniqueKey, State = "XX", PreferredCallTime = TimeOnly.FromDateTime(DateTime.Now)
            };
            var cust2 = new CustomerWithTime()
            {
                FullName = uniqueKey, State = "XX", PreferredCallTime = TimeOnly.FromDateTime(DateTime.Now)
            };
            var cust3 = new CustomerWithTime()
            {
                FullName = uniqueKey, State = "XX", PreferredCallTime = TimeOnly.FromDateTime(DateTime.Now)
            };
            dataSource.Insert(CustomerTableName, cust1).Execute();
            dataSource.Insert(CustomerTableName, cust2).Execute();
            dataSource.Insert(CustomerTableName, cust3).Execute();

            var lookup = dataSource.From(CustomerTableName, new { FullName = uniqueKey }).WithSorting("CustomerKey").ToCollection <CustomerWithTime>().Execute();

            //To account for rounding, allow a 1 ms delta
            Assert.IsTrue(cust1.PreferredCallTime.Ticks - lookup[0].PreferredCallTime.Ticks < TimeSpanDelta, $"Actual difference was {cust1.PreferredCallTime.Ticks - lookup[0].PreferredCallTime.Ticks}");
        }
        finally
        {
            Release(dataSource);
        }
    }
            /// <summary>
            /// Gets a valid IG account.
            /// </summary>
            /// <returns>An IG Account</returns>
            /// <exception cref="InvalidDataException">No accounts avaliable</exception>
            public static IGAccount GetIGAccount()
            {
                //Randomize the accounts
                Random rand             = new Random();
                var    shuffledAccounts = Accounts.OrderBy(x => rand.Next()).ToList();

                //Find a valid account
                foreach (IGAccount cred in shuffledAccounts)
                {
                    TimeOnly timeNow = TimeOnly.FromDateTime(DateTime.Now);
                    if (!cred.Blacklist)
                    {
                        if (cred.UsageTimes != null && cred.UsageTimes.Count > 0)
                        {
                            // Check valid times:
                            foreach (IGAccount.OperatingTime time in cred.UsageTimes)
                            {
                                if (time.BetweenStartAndEnd(timeNow))
                                {
                                    return(cred);
                                }
                            }
                        }
                        else
                        {
                            // Warn about not setting valid times:
                            Console.WriteLine("Warning: No time set on account " + cred.UserName + ". Using the account.");
                            return(cred);
                        }
                    }
                }
                throw new InvalidDataException("No available accounts.");
            }
 private void InitHouseStateTimeOfDay()
 {
     _log.LogTrace("InitHouseStateTimeOfDay");
     if (TimeOnly.FromDateTime(DateTime.Now).IsBetween(Constants.NIGHT_START, Constants.NIGHT_END) &&
         _entities.InputSelect.TimeOfDay.IsNotOption(TimeOfDayOptions.Night))
     {
         _log.LogTrace("Setting time of day to Night");
         _entities.InputSelect.TimeOfDay.SelectOption(TimeOfDayOptions.Night);
     }
     else if (TimeOnly.FromDateTime(DateTime.Now).IsBetween(Constants.NIGHT_END, Constants.MORNING_END) &&
              _entities.InputSelect.TimeOfDay.IsNotOption(TimeOfDayOptions.Morning))
     {
         _log.LogTrace("Setting time of day to Morning");
         _entities.InputSelect.TimeOfDay.SelectOption(TimeOfDayOptions.Morning);
     }
     else if (TimeOnly.FromDateTime(DateTime.Now).IsBetween(Constants.MORNING_END, Constants.NIGHT_START) &&
              _entities.Sun.Sun.State == "above_horizon" &&
              _entities.InputSelect.TimeOfDay.IsNotOption(TimeOfDayOptions.Day))
     {
         _log.LogTrace("Setting time of day to Day");
         _entities.InputSelect.TimeOfDay.SelectOption(TimeOfDayOptions.Day);
     }
     else if (_entities.InputSelect.TimeOfDay.IsNotOption(TimeOfDayOptions.Evening))
     {
         _log.LogTrace("Setting time of day to Evening");
         _entities.InputSelect.TimeOfDay.SelectOption(TimeOfDayOptions.Evening);
     }
 }
示例#4
0
        /// <summary>
        /// Get a <see cref="TimeOnly"/> that will happen soon.
        /// </summary>
        /// <param name="mins">Minutes no more than <paramref name="mins"/> ahead.</param>
        /// <param name="refTime">The time to start calculations. Default is time from <see cref="DateTime.Now"/>.</param>
        public TimeOnly SoonTimeOnly(int mins = 60, TimeOnly?refTime = null)
        {
            var start      = refTime ?? TimeOnly.FromDateTime(SystemClock());
            var maxForward = start.AddMinutes(mins);

            return(BetweenTimeOnly(start, maxForward));
        }
示例#5
0
        /// <summary>
        /// Get a random <see cref="TimeOnly"/> within the last few Minutes.
        /// </summary>
        /// <param name="mins">Minutes <paramref name="mins"/> of the day to go back.</param>
        /// <param name="refTime">The Time to start calculations. Default is time from <see cref="DateTime.Now"/>.</param>
        public TimeOnly RecentTimeOnly(int mins = 60, TimeOnly?refTime = null)
        {
            var start     = refTime ?? TimeOnly.FromDateTime(SystemClock());
            var maxBehind = start.AddMinutes(-mins);

            return(BetweenTimeOnly(maxBehind, start));
        }
示例#6
0
        public static void OAndRFormatsTest()
        {
            TimeOnly timeOnly      = TimeOnly.FromDateTime(DateTime.Now);
            string   formattedDate = timeOnly.ToString("o");

            Assert.Equal(16, formattedDate.Length);
            Assert.Equal(':', formattedDate[2]);
            Assert.Equal(':', formattedDate[5]);
            Assert.Equal('.', formattedDate[8]);
            TimeOnly parsedTimeOnly = TimeOnly.Parse(formattedDate);

            Assert.Equal(timeOnly, parsedTimeOnly);
            parsedTimeOnly = TimeOnly.Parse(formattedDate.AsSpan());
            Assert.Equal(timeOnly, parsedTimeOnly);
            parsedTimeOnly = TimeOnly.ParseExact(formattedDate, "O");
            Assert.Equal(timeOnly, parsedTimeOnly);
            parsedTimeOnly = TimeOnly.ParseExact(formattedDate.AsSpan(), "O".AsSpan());
            Assert.Equal(timeOnly, parsedTimeOnly);

            timeOnly      = new TimeOnly(timeOnly.Hour, timeOnly.Minute, timeOnly.Second);
            formattedDate = timeOnly.ToString("r");
            Assert.Equal(8, formattedDate.Length);
            Assert.Equal(':', formattedDate[2]);
            Assert.Equal(':', formattedDate[5]);
            parsedTimeOnly = TimeOnly.Parse(formattedDate);
            Assert.Equal(timeOnly, parsedTimeOnly);
            parsedTimeOnly = TimeOnly.Parse(formattedDate.AsSpan());
            Assert.Equal(timeOnly, parsedTimeOnly);
            parsedTimeOnly = TimeOnly.ParseExact(formattedDate, "R");
            Assert.Equal(timeOnly, parsedTimeOnly);
            parsedTimeOnly = TimeOnly.ParseExact(formattedDate.AsSpan(), "R".AsSpan());
            Assert.Equal(timeOnly, parsedTimeOnly);
        }
示例#7
0
        public static void TryFormatTest()
        {
            Span <char> buffer   = stackalloc char[100];
            TimeOnly    timeOnly = TimeOnly.FromDateTime(DateTime.Now);

            buffer.Fill(' ');
            Assert.True(timeOnly.TryFormat(buffer, out int charsWritten));
            Assert.Equal(charsWritten, buffer.TrimEnd().Length);

            buffer.Fill(' ');
            Assert.True(timeOnly.TryFormat(buffer, out charsWritten, "o"));
            Assert.Equal(16, charsWritten);
            Assert.Equal(16, buffer.TrimEnd().Length);

            buffer.Fill(' ');
            Assert.True(timeOnly.TryFormat(buffer, out charsWritten, "R"));
            Assert.Equal(8, charsWritten);
            Assert.Equal(8, buffer.TrimEnd().Length);

            Assert.False(timeOnly.TryFormat(buffer.Slice(0, 3), out charsWritten));
            Assert.False(timeOnly.TryFormat(buffer.Slice(0, 3), out charsWritten, "r"));
            Assert.False(timeOnly.TryFormat(buffer.Slice(0, 3), out charsWritten, "O"));

            Assert.Throws <FormatException>(() => {
                Span <char> buff = stackalloc char[100];
                timeOnly.TryFormat(buff, out charsWritten, "u");
            });
            Assert.Throws <FormatException>(() => {
                Span <char> buff = stackalloc char[100];
                timeOnly.TryFormat(buff, out charsWritten, "dd-yyyy");
            });
            Assert.Throws <FormatException>(() => $"{timeOnly:u}");
            Assert.Throws <FormatException>(() => $"{timeOnly:dd-yyyy}");
        }
示例#8
0
 /// <summary>
 /// Creates a new instance of this converter.
 /// </summary>
 public NullableTimeOnlyConverter() : base(
         t => t == null
         ? null
         : DateTime.MinValue.Add(t.Value.ToTimeSpan()),
         d => d == null
         ? null
         : TimeOnly.FromDateTime(d.Value))
 {
 }
示例#9
0
        public static void GetHashCodeTest()
        {
            TimeOnly timeOnly1 = TimeOnly.FromDateTime(DateTime.Now);
            TimeOnly timeOnly2 = timeOnly1.Add(new TimeSpan(1));
            TimeOnly timeOnly3 = new TimeOnly(timeOnly1.Ticks);

            Assert.True(timeOnly1.GetHashCode() == timeOnly3.GetHashCode());
            Assert.False(timeOnly1.GetHashCode() == timeOnly2.GetHashCode());
        }
示例#10
0
        public static void FromDateTimeTest()
        {
            DateTime dt       = DateTime.Now;
            TimeOnly timeOnly = TimeOnly.FromDateTime(dt);

            Assert.Equal(dt.Hour, timeOnly.Hour);
            Assert.Equal(dt.Minute, timeOnly.Minute);
            Assert.Equal(dt.Second, timeOnly.Second);
            Assert.Equal(dt.Millisecond, timeOnly.Millisecond);
            Assert.Equal(dt.TimeOfDay.Ticks, timeOnly.Ticks);
        }
示例#11
0
    public void FormatValue_TimeOnly_Format()
    {
        // Arrange
        var value    = TimeOnly.FromDateTime(DateTime.Now);
        var expected = value.ToString("HH:mm", CultureInfo.InvariantCulture);

        // Act
        var actual = BindConverter.FormatValue(value, "HH:mm", CultureInfo.InvariantCulture);

        // Assert
        Assert.Equal(expected, actual);
    }
示例#12
0
    public virtual async Task TimeOnly_FromDateTime_with_timestamp(bool async)
    {
        await AssertQuery(
            async,
            ss => ss.Set <Entity>().Where(
                e => TimeOnly.FromDateTime(e.TimestampDateTime) == new TimeOnly(15, 26, 38)),
            entryCount : 1);

        AssertSql(
            @"SELECT e.""Id"", e.""TimestampDateTime"", e.""TimestampDateTimeArray"", e.""TimestampDateTimeOffset"", e.""TimestampDateTimeOffsetArray"", e.""TimestampDateTimeRange"", e.""TimestamptzDateTime"", e.""TimestamptzDateTimeArray"", e.""TimestamptzDateTimeRange""
FROM ""Entities"" AS e
WHERE e.""TimestampDateTime""::time without time zone = TIME '15:26:38'");
    }
示例#13
0
    public virtual async Task TimeOnly_ToTimeSpan(bool async)
    {
        await AssertQuery(
            async,
            ss => ss.Set <Entity>().Where(
                e => TimeOnly.FromDateTime(e.TimestamptzDateTime) == new TimeOnly(13, 26, 38)),
            entryCount : 1);

        AssertSql(
            @"SELECT e.""Id"", e.""TimestampDateTime"", e.""TimestampDateTimeArray"", e.""TimestampDateTimeOffset"", e.""TimestampDateTimeOffsetArray"", e.""TimestampDateTimeRange"", e.""TimestamptzDateTime"", e.""TimestamptzDateTimeArray"", e.""TimestamptzDateTimeRange""
FROM ""Entities"" AS e
WHERE CAST((e.""TimestamptzDateTime"" AT TIME ZONE 'UTC') AS time without time zone) = TIME '13:26:38'");
    }
    public void MapsTo_DateTimeOffset()
    {
        var mapper = Config.CreateMapper();

        var foo = new Foo5
        {
            Bar = TimeOnly.FromDateTime(DateTime.Now)
        };

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

        result.Should().Be(foo.Bar.ToLocalTime());
    }
示例#15
0
 /// <summary>
 ///     Set to evening when the light level is low and it is daytime
 /// </summary>
 private void SetEveningWhenLowLightLevel()
 {
     _entities.Sensor.WeatherStationAmbientLight
     .StateAllChangesWithCurrent()
     .Where(e => e.New?.State <= Constants.DARK_THRESHOLD &&
            TimeOnly.FromDateTime(DateTime.Now).IsBetween(Constants.EVENING_START, Constants.EVENING_END))
     .Subscribe(s =>
     {
         if (SetTimeOfDay(TimeOfDayOptions.Evening))
         {
             _log.LogInformation($"Setting Time Of Day to Evening - Light level below dark threshold and time within evening range.");
         }
     });
 }
示例#16
0
        public static void TryFormatTest()
        {
            Span <char> buffer   = stackalloc char[100];
            TimeOnly    timeOnly = TimeOnly.FromDateTime(DateTime.Now);

            Assert.True(timeOnly.TryFormat(buffer, out int charsWritten));
            Assert.True(timeOnly.TryFormat(buffer, out charsWritten, "o"));
            Assert.Equal(16, charsWritten);
            Assert.True(timeOnly.TryFormat(buffer, out charsWritten, "R"));
            Assert.Equal(8, charsWritten);
            Assert.False(timeOnly.TryFormat(buffer.Slice(0, 3), out charsWritten));
            Assert.False(timeOnly.TryFormat(buffer.Slice(0, 3), out charsWritten, "r"));
            Assert.False(timeOnly.TryFormat(buffer.Slice(0, 3), out charsWritten, "O"));
        }
示例#17
0
        public static void CustomFormattingTest()
        {
            TimeOnly timeOnly       = TimeOnly.FromDateTime(DateTime.Now);
            string   format         = "HH 'dash' mm \"dash\" ss'....'fffffff";
            string   formatted      = timeOnly.ToString(format);
            TimeOnly parsedTimeOnly = TimeOnly.ParseExact(formatted, format);

            Assert.Equal(timeOnly, parsedTimeOnly);
            parsedTimeOnly = TimeOnly.ParseExact(formatted.AsSpan(), format.AsSpan());
            Assert.Equal(timeOnly, parsedTimeOnly);

            Assert.Throws <FormatException>(() => timeOnly.ToString("hh:mm:ss dd"));
            Assert.Throws <FormatException>(() => timeOnly.ToString("hh:mm:ss MM"));
            Assert.Throws <FormatException>(() => timeOnly.ToString("hh:mm:ss yy"));
        }
示例#18
0
 /// <summary>
 ///     When the light levels are bright enough it is considered morning time
 /// </summary>
 private void SetMorningWhenBrightLightLevel()
 {
     _entities.Sensor.WeatherStationAmbientLight
     .StateAllChangesWithCurrent()
     .Where(e => e.New?.State > Constants.DARK_THRESHOLD &&
            TimeOnly.FromDateTime(DateTime.Now).IsBetween(Constants.MORNING_START, Constants.MORNING_END) &&
            _entities.Sun.Sun?.Attributes?.Rising == true)
     .Subscribe(s =>
     {
         if (SetTimeOfDay(TimeOfDayOptions.Morning))
         {
             _log.LogInformation($"Setting Time Of Day to Morning - Light level above dark threshold and time within morning range.");
         }
     });
 }
示例#19
0
        public static void ConvertFrom_TimeOnlyInstanceDescriptor()
        {
            using (new ThreadCultureChange("fr-FR"))
            {
                TimeOnly        testTimeOnly = TimeOnly.FromDateTime(DateTime.UtcNow);
                ConstructorInfo ctor         = typeof(TimeOnly).GetConstructor(new Type[]
                {
                    typeof(int), typeof(int), typeof(int), typeof(int), typeof(int)
                });

                InstanceDescriptor descriptor = new InstanceDescriptor(ctor, new object[]
                {
                    testTimeOnly.Hour, testTimeOnly.Minute, testTimeOnly.Second, testTimeOnly.Millisecond, testTimeOnly.Microsecond
                });

                const string format = "HH mm ss fff tt";
                object       o      = s_converter.ConvertFrom(descriptor);
                Assert.Equal(testTimeOnly.ToString(format), ((TimeOnly)o).ToString(format));
            }
        }
        public void ConvertFromStringTest()
        {
            var converter = new TimeOnlyConverter();

            var propertyMapData = new MemberMapData(null);

            propertyMapData.TypeConverterOptions.CultureInfo = CultureInfo.CurrentCulture;

            var row = new CsvReader(new ParserMock());

            var time = TimeOnly.FromDateTime(DateTime.Now);

            // Valid conversions.
            Assert.Equal(time.ToString(), converter.ConvertFromString(time.ToString(), null, propertyMapData).ToString());
            Assert.Equal(time.ToString(), converter.ConvertFromString(time.ToString("o"), null, propertyMapData).ToString());
            Assert.Equal(time.ToString(), converter.ConvertFromString(" " + time + " ", null, propertyMapData).ToString());

            // Invalid conversions.
            Assert.Throws <TypeConverterException>(() => converter.ConvertFromString(null, row, propertyMapData));
        }
        public static string ToLabelString(
            this TimeFormat format,
            DateTimeSettings currentSettings,
            DateTime sampleTime
            )
        {
            string label;

            if (format == TimeFormat.Hour24)
            {
                label = "24 Hour";
            }
            else // 12 Hour is the default.
            {
                label = "12 Hour";
            }

            DateTimeSettings settings = currentSettings with {
                TimeFormat = format
            };
            var time = TimeOnly.FromDateTime(sampleTime);

            return($"{label} ({time.ToSettingsString( settings )})");
        }
示例#22
0
        public static void ComparisonsTest()
        {
            TimeOnly timeOnly1 = TimeOnly.FromDateTime(DateTime.Now);
            TimeOnly timeOnly2 = timeOnly1.Add(new TimeSpan(1));
            TimeOnly timeOnly3 = new TimeOnly(timeOnly1.Ticks);

            Assert.Equal(-1, timeOnly1.CompareTo(timeOnly2));
            Assert.Equal(1, timeOnly2.CompareTo(timeOnly1));
            Assert.Equal(-1, timeOnly1.CompareTo(timeOnly2));
            Assert.Equal(0, timeOnly1.CompareTo(timeOnly3));

            Assert.Equal(-1, timeOnly1.CompareTo((object)timeOnly2));
            Assert.Equal(1, timeOnly2.CompareTo((object)timeOnly1));
            Assert.Equal(-1, timeOnly1.CompareTo((object)timeOnly2));
            Assert.Equal(0, timeOnly1.CompareTo((object)timeOnly3));

            Assert.True(timeOnly1.Equals(timeOnly3));
            Assert.True(timeOnly1.Equals((object)timeOnly3));
            Assert.False(timeOnly2.Equals(timeOnly3));
            Assert.False(timeOnly2.Equals((object)timeOnly3));

            Assert.False(timeOnly2.Equals(null));
            Assert.False(timeOnly2.Equals(new object()));
        }
示例#23
0
        /// <summary>
        /// Sets <paramref name="value"/> on the property defined by <paramref name="memberInfo"/> on <paramref name="entity"/>.
        /// </summary>
        /// <param name="memberInfo"></param>
        /// <param name="value"></param>
        /// <param name="entity"></param>
        public static void SetMemberValue(MemberInfo memberInfo, object value, object entity)
        {
            // if this is a nullable type, we need to get the underlying type (ie. int?, float?, guid?, etc.)
            var type           = GetMemberType(memberInfo);
            var underlyingType = Nullable.GetUnderlyingType(type);

            if (underlyingType != null)
            {
                type = underlyingType;
            }

            if (value == DBNull.Value)
            {
                value = null;
            }
            else
            {
                value = ConvertValueToEnum(value, type);
            }

            // custom support for converting to DateOnly and TimeOnly
            if (type == typeof(DateOnly) && value is DateTime dt1)
            {
                value = DateOnly.FromDateTime(dt1);
            }
            else if (type == typeof(TimeOnly))
            {
                switch (value)
                {
                case DateTime dt2:
                    value = TimeOnly.FromDateTime(dt2);
                    break;

                case TimeSpan ts:
                    value = TimeOnly.FromTimeSpan(ts);
                    break;
                }
            }

            try
            {
                switch (memberInfo.MemberType)
                {
                case MemberTypes.Field:
                    ((FieldInfo)memberInfo).SetValue(entity, value);
                    break;

                case MemberTypes.Property:
                    ((PropertyInfo)memberInfo).SetValue(entity, value, null);
                    break;

                default:
                    throw new ArgumentException($"Only {MemberTypes.Field} and {MemberTypes.Property} are supported.", nameof(memberInfo));
                }
            }
            catch (Exception innerException)
            {
                string valueType = value == null ? "unknown (=NULL)" : value.GetType().ToString();
                string message   = $"Error while setting the {memberInfo.Name} member with an object of type {value}";

                throw new Exception(message, innerException);
            }
        }
示例#24
0
        public static void FormatParseTest()
        {
            string[] patterns = new string[] { CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern, CultureInfo.CurrentCulture.DateTimeFormat.LongTimePattern, "t", "T", "o", "r" };

            TimeOnly timeOnly = TimeOnly.FromDateTime(DateTime.Now);

            foreach (string format in patterns)
            {
                string formattedTime = timeOnly.ToString(format);
                timeOnly = TimeOnly.Parse(formattedTime);

                Assert.True(TimeOnly.TryParse(formattedTime, out TimeOnly parsedTimeOnly1));
                Assert.Equal(timeOnly, parsedTimeOnly1);
                TimeOnly parsedTimeOnly = TimeOnly.Parse(formattedTime.AsSpan());
                Assert.True(TimeOnly.TryParse(formattedTime.AsSpan(), out parsedTimeOnly1));
                Assert.Equal(timeOnly, parsedTimeOnly);
                Assert.Equal(timeOnly, parsedTimeOnly1);

                parsedTimeOnly = TimeOnly.Parse(formattedTime, CultureInfo.CurrentCulture);
                Assert.True(TimeOnly.TryParse(formattedTime, CultureInfo.CurrentCulture, DateTimeStyles.None, out parsedTimeOnly1));
                Assert.Equal(timeOnly, parsedTimeOnly);
                Assert.Equal(timeOnly, parsedTimeOnly1);
                parsedTimeOnly = TimeOnly.Parse(formattedTime.AsSpan(), CultureInfo.CurrentCulture);
                Assert.True(TimeOnly.TryParse(formattedTime.AsSpan(), CultureInfo.CurrentCulture, DateTimeStyles.None, out parsedTimeOnly1));
                Assert.Equal(timeOnly, parsedTimeOnly);
                Assert.Equal(timeOnly, parsedTimeOnly1);

                parsedTimeOnly = TimeOnly.ParseExact(formattedTime, format);
                Assert.True(TimeOnly.TryParseExact(formattedTime, format, out parsedTimeOnly1));
                Assert.Equal(timeOnly, parsedTimeOnly);
                Assert.Equal(timeOnly, parsedTimeOnly1);
                parsedTimeOnly = TimeOnly.ParseExact(formattedTime.AsSpan(), format.AsSpan());
                Assert.True(TimeOnly.TryParseExact(formattedTime.AsSpan(), format.AsSpan(), out parsedTimeOnly1));
                Assert.Equal(timeOnly, parsedTimeOnly);
                Assert.Equal(timeOnly, parsedTimeOnly1);

                parsedTimeOnly = TimeOnly.ParseExact(formattedTime, format, CultureInfo.CurrentCulture);
                Assert.True(TimeOnly.TryParseExact(formattedTime, format, CultureInfo.CurrentCulture, DateTimeStyles.None, out parsedTimeOnly1));
                Assert.Equal(timeOnly, parsedTimeOnly);
                Assert.Equal(timeOnly, parsedTimeOnly1);
                parsedTimeOnly = TimeOnly.ParseExact(formattedTime.AsSpan(), format.AsSpan(), CultureInfo.CurrentCulture);
                Assert.True(TimeOnly.TryParseExact(formattedTime.AsSpan(), format.AsSpan(), CultureInfo.CurrentCulture, DateTimeStyles.None, out parsedTimeOnly1));
                Assert.Equal(timeOnly, parsedTimeOnly);
                Assert.Equal(timeOnly, parsedTimeOnly1);

                parsedTimeOnly = TimeOnly.ParseExact(formattedTime, patterns);
                Assert.True(TimeOnly.TryParseExact(formattedTime, patterns, out parsedTimeOnly1));
                Assert.Equal(timeOnly, parsedTimeOnly);
                Assert.Equal(timeOnly, parsedTimeOnly1);
                parsedTimeOnly = TimeOnly.ParseExact(formattedTime.AsSpan(), patterns);
                Assert.True(TimeOnly.TryParseExact(formattedTime.AsSpan(), patterns, out parsedTimeOnly1));
                Assert.Equal(timeOnly, parsedTimeOnly);
                Assert.Equal(timeOnly, parsedTimeOnly1);

                parsedTimeOnly = TimeOnly.ParseExact(formattedTime, patterns, CultureInfo.CurrentCulture);
                Assert.True(TimeOnly.TryParseExact(formattedTime, patterns, CultureInfo.CurrentCulture, DateTimeStyles.None, out parsedTimeOnly1));
                Assert.Equal(timeOnly, parsedTimeOnly);
                Assert.Equal(timeOnly, parsedTimeOnly1);
                parsedTimeOnly = TimeOnly.ParseExact(formattedTime.AsSpan(), patterns, CultureInfo.CurrentCulture);
                Assert.True(TimeOnly.TryParseExact(formattedTime.AsSpan(), patterns, CultureInfo.CurrentCulture, DateTimeStyles.None, out parsedTimeOnly1));
                Assert.Equal(timeOnly, parsedTimeOnly);
                Assert.Equal(timeOnly, parsedTimeOnly1);
            }
        }
示例#25
0
 internal static DyObject Time(ExecutionContext ctx, DyDateTime self) => new DyTime(ctx.Type <DyTimeTypeInfo>(), TimeOnly.FromDateTime(new DateTime(self.TotalTicks)).Ticks);
示例#26
0
    public void ToObject_TimeOnlyColumn(string dataSourceName, DataSourceType mode)
    {
        var dataSource = DataSource(dataSourceName, mode);

        try
        {
            var cust = new CustomerWithTime()
            {
                FullName = Guid.NewGuid().ToString(), State = "XX", PreferredCallTime = TimeOnly.FromDateTime(DateTime.Now)
            };
            var key = dataSource.Insert(CustomerTableName, cust).ToInt32().Execute();

            var lookup = dataSource.GetByKey(CustomerTableName, key).ToObject <CustomerWithTime>().Execute();

            //To account for rounding, allow a 1 ms delta
            Assert.IsTrue(cust.PreferredCallTime.Ticks - lookup.PreferredCallTime.Ticks < TimeSpanDelta, $"Actual difference was {cust.PreferredCallTime.Ticks - lookup.PreferredCallTime.Ticks}");
        }
        finally
        {
            Release(dataSource);
        }
    }
        /// <summary>
        /// Turns the current or provided time into a human readable sentence
        /// </summary>
        /// <param name="input">The date to be humanized</param>
        /// <param name="useUtc">If <paramref name="timeToCompareAgainst"/> is null, used to determine if the current time is UTC or local. Defaults to UTC.</param>
        /// <param name="timeToCompareAgainst">Date to compare the input against. If null, current date is used as base</param>
        /// <param name="culture">Culture to use. If null, current thread's UI culture is used.</param>
        /// <returns>distance of time in words</returns>
        public static string Humanize(this TimeOnly input, TimeOnly?timeToCompareAgainst = null, bool useUtc = true, CultureInfo culture = null)
        {
            var comparisonBase = timeToCompareAgainst.HasValue ? timeToCompareAgainst.Value : TimeOnly.FromDateTime(useUtc ? DateTime.UtcNow : DateTime.Now);

            return(Configurator.TimeOnlyHumanizeStrategy.Humanize(input, comparisonBase, culture));
        }