Exemple #1
0
 public void SetPosition(DateTime when, DateTimeKind whenKind, double latitudeDegrees, double longitudeDegrees)
 {
   IntPtr pSun = NonConstPointer();
   UnsafeNativeMethods.Rdk_Sun_SetLatitudeLongitude(pSun, latitudeDegrees, longitudeDegrees);
   bool local = whenKind != DateTimeKind.Utc;
   UnsafeNativeMethods.Rdk_Sun_SetDateTime(pSun, local, when.Year, when.Month, when.Day, when.Hour, when.Minute, when.Second);
 }
        /// <summary>
        /// Gets the Minimum value for a DateTime specifying kind.
        /// </summary>
        /// <param name="kind">DateTimeKind to use.</param>
        /// <returns>DateTime of specified kind.</returns>
        public static DateTime GetMinValue(DateTimeKind kind)
        {
            if (kind == DateTimeKind.Unspecified)
                return new DateTime(DateTime.MinValue.Ticks, DateTimeKind.Utc);

            return new DateTime(DateTime.MinValue.Ticks, kind);
        }
		private static void DoTest(DateTime dt, DateTimeKind inKind, DateTimeKind outKind)
		{
			Assert.Equal(inKind, dt.Kind);

			using (var documentStore = new EmbeddableDocumentStore { RunInMemory = true })
			{
				documentStore.Initialize();

				using (var session = documentStore.OpenSession())
				{
					session.Store(new Foo { Id = "foos/1", DateTime = dt });
					session.SaveChanges();
				}

				using (var session = documentStore.OpenSession())
				{
					var foo = session.Query<Foo>()
									 .Customize(x => x.WaitForNonStaleResults())
									 .FirstOrDefault(x => x.DateTime == dt);

					WaitForUserToContinueTheTest(documentStore);

					Assert.Equal(dt, foo.DateTime);
					Assert.Equal(outKind, foo.DateTime.Kind);
				}
			}
		}
Exemple #4
0
        public DateParser(string format, DateTimeKind kind)
        {
            switch (kind)
            {
                case DateTimeKind.Local:
                    _style = DateTimeStyles.AssumeLocal;
                    break;

                case DateTimeKind.Utc:
                    _style = DateTimeStyles.AssumeUniversal;
                    break;

                default:
                    throw new ArgumentOutOfRangeException("kind");
            }

            switch (format)
            {
                case "ABSOLUTE":
                    break;

                case "ISO8601":
                    break;

                case "DATE":
                    break;
            }
        }
Exemple #5
0
        /// <summary>
        /// 現在のインスタンスと比較します。
        /// </summary>
        /// <param name="self">自分自身</param>
        /// <param name="value">比較する値</param>
        /// <param name="compareKind">比較する時間の種別</param>
        /// <returns>比較結果(true:一致, false:不一致)</returns>
        public static bool Compare(this DateTime self, DateTime value, DateTimeKind compareKind)
        {
            var ts = self - value;
            double total = 0D;
            double sub = 1.0D;

            switch (compareKind)
            {
                case DateTimeKind.Year:
                    total = self.Year - value.Year;
                    break;
                case DateTimeKind.Month:
                    sub = 30.0D;
                    total = ts.TotalDays;
                    break;
                case DateTimeKind.Day:
                    total = ts.TotalDays;
                    break;
                case DateTimeKind.Hour:
                    total = ts.TotalHours;
                    break;
                case DateTimeKind.Minute:
                    total = ts.TotalMinutes;
                    break;
                case DateTimeKind.Second:
                    total = ts.TotalSeconds;
                    break;
                case DateTimeKind.Milliseconds:
                    total = ts.TotalMilliseconds;
                    break;
            }

            return Math.Abs(total) < sub;
        }
 /// <summary>
 /// Initializes a new instance of the DateTimeSerializationOptions class.
 /// </summary>
 /// <param name="kind">The DateTimeKind (Local, Unspecified or Utc).</param>
 /// <param name="representation">The external representation.</param>
 public DateTimeSerializationOptions(
     DateTimeKind kind,
     BsonType representation
 ) {
     this.kind = kind;
     this.representation = representation;
 }
 public static DateTime GetDateInUserTimeZone(DateTime sourceDate, DateTimeKind sourceDateTimeKind, User user)
 {
     sourceDate = DateTime.SpecifyKind(sourceDate, sourceDateTimeKind);
     //get the timezone of mentioned user
     var userTimezoneId = user.GetPropertyValueAs<string>(PropertyNames.DefaultTimeZoneId);
     if (string.IsNullOrEmpty(userTimezoneId))
     {
         //get default timezone
         var generalSettings = mobSocialEngine.ActiveEngine.Resolve<GeneralSettings>();
         userTimezoneId = generalSettings.DefaultTimeZoneId;
     }
     //let's find the timezone
     TimeZoneInfo timeZoneInfo;
     try
     {
         timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(userTimezoneId);
     }
     catch
     {
         //in case of error let's default to local timezone
         timeZoneInfo = TimeZoneInfo.Local;
     }
     //get the timezone
     return GetDateInTimeZone(sourceDate, timeZoneInfo);
 }
Exemple #8
0
        /// <summary>
        /// Obtient une date dans le kind spécifié en fonction des paramètres spécifiés
        /// </summary>
        /// <param name="rule"><see cref="RuleDate"/> décrivant la date</param>
        /// <param name="year">Année de la date</param>
        /// <param name="gmtOffset">Offset gmt dans lequel est exprimé la date</param>
        /// <param name="stdOffset">Offset standard dans lequel est exprimé la date</param>
        /// <param name="dateTimeKind"><see cref="DateTimeKind"/> dans lequel exprimer la date</param>
        /// <returns><see cref="DateTime"/> du kind spécifié correspondant aux paramètres spécifiés</returns>
        public static DateTime GetDateTime(RuleDate rule, int year, TimeSpan gmtOffset, TimeSpan stdOffset, DateTimeKind dateTimeKind)
        {
            if (dateTimeKind == DateTimeKind.Unspecified) throw new ArgumentException("Unspecified date time kind", "dateTimeKind");

            if (dateTimeKind == DateTimeKind.Local)
                return GetWallClockTime(rule, year, gmtOffset, stdOffset);
            return GetUTCTime(rule, year, gmtOffset, stdOffset);
        }
 public static SharpMapillaryInfo LoadJPEG(this SharpMapillaryInfo           MapillaryInfo,
                                           String                            JPEGFile,
                                           DateTimeKind                      DateTimeType         = DateTimeKind.Utc,
                                           Int32?                            TimeOffset           = null,
                                           Func<String, DateTime, DateTime>  OnDupliateTimestamp  = null)
 {
     return LoadJPEG(JPEGFile, ref MapillaryInfo, DateTimeType, TimeOffset, OnDupliateTimestamp);
 }
        /// <summary>
        ///     Returns DateTime created from an integer in the YYYYMMDD, YYYYMMDDHHmmss, or YYYYMMDDHHmmssFFF format.
        /// </summary>
        /// <param name="sortableDateTime"></param>
        /// <param name="dtKind"></param>
        /// <returns></returns>
        public static DateTime? FromSortableIntDateTime(this string sortableDateTime, DateTimeKind dtKind = DateTimeKind.Unspecified)
        {
            long? sortableVal = sortableDateTime.ParseLong();
            if(sortableVal == null)
                return null;

            return sortableVal.Value.FromSortableIntDateTime(dtKind);
        }
 public DateTimeDataType(int id, string name, string alias, DataType basic, DataType parent, bool editable,
     DateTimeKind part, DateTime minValue, DateTime maxValue, bool nullable)
     : base(id, name, alias, basic, parent, editable, nullable)
 {
     this.part = part;
     this.minValue = minValue;
     this.maxValue = maxValue;
 }
Exemple #12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BsonReader"/> class.
 /// </summary>
 /// <param name="stream">The stream.</param>
 /// <param name="readRootValueAsArray">if set to <c>true</c> the root object will be read as a JSON array.</param>
 /// <param name="dateTimeKindHandling">The <see cref="DateTimeKind" /> used when reading <see cref="DateTime"/> values from BSON.</param>
 public BsonReader(Stream stream, bool readRootValueAsArray, DateTimeKind dateTimeKindHandling)
 {
     ValidationUtils.ArgumentNotNull(stream, "stream");
     _reader = new BinaryReader(stream);
     _stack = new List<ContainerContext>();
     _readRootValueAsArray = readRootValueAsArray;
     _dateTimeKindHandling = dateTimeKindHandling;
 }
Exemple #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UserDataRule" /> class.
 /// </summary>
 /// <param name="columnName">Name of the column.</param>
 /// <param name="kind">The kind.</param>
 /// <param name="appliesWhen">The rule can be applied to insert, update, and/or soft delete operations.</param>
 /// <exception cref="ArgumentOutOfRangeException">appliesWhen;appliesWhen may only be a combination of Insert, Update, or Delete</exception>
 /// <remarks>
 /// This will have no effect on hard deletes.
 /// </remarks>
 public DateTimeRule(string columnName, DateTimeKind kind, OperationTypes appliesWhen) : base(columnName, appliesWhen)
 {
     if (appliesWhen.HasFlag(OperationTypes.Select))
         throw new ArgumentOutOfRangeException("appliesWhen", appliesWhen, "appliesWhen may only be a combination of Insert, Update, or Delete");
     if (kind == DateTimeKind.Unspecified)
         throw new ArgumentOutOfRangeException("kind");
     Kind = kind;
 }
        public __DateTime()
        {
            this.Kind = DateTimeKind.Local;
            // fix for default(DateTime).ToString
            // X:\jsc.svn\examples\javascript\Test\TestDateTime\TestDateTime\Program.cs
            this.InternalValue = new IDate();

        }
        public static SharpMapillaryInfo LoadJPEG(this String                       JPEGFile,
                                                  DateTimeKind                      DateTimeType         = DateTimeKind.Utc,
                                                  Int32?                            TimeOffset           = null,
                                                  Func<String, DateTime, DateTime>  OnDupliateTimestamp  = null)
        {
            var Mapillary = new SharpMapillaryInfo(JPEGFile.Substring(0, JPEGFile.LastIndexOf(Path.DirectorySeparatorChar)));

            return LoadJPEG(JPEGFile, ref Mapillary, DateTimeType, TimeOffset, OnDupliateTimestamp);
        }
 public DateTime GetCurrentTime(DateTimeKind dateTimeKind)
 {
     switch (dateTimeKind)
     {
         case DateTimeKind.Local: return DateTime.Now.ToLocalTime();
         case DateTimeKind.Utc: return DateTime.Now.ToUniversalTime();
         default: return DateTime.Now;
     }
 }
    public static DateTime GetContextNow( DateTimeKind kind )
    {
      if( kind == DateTimeKind.Unspecified )
        return DateTime.SpecifyKind( DateTime.Now, DateTimeKind.Unspecified );

      return ( kind == DateTimeKind.Utc )
        ? DateTime.UtcNow
        : DateTime.Now;
    }
        public static DateTime? SpecifyKindIfUnspecified(DateTime? dateTime, DateTimeKind kind)
        {
            if (dateTime == null)
            {
                return null;
            }

            return dateTime.Value.Kind == DateTimeKind.Unspecified ? DateTime.SpecifyKind(dateTime.Value, kind) : dateTime;
        }
Exemple #19
0
 /// <summary>
 /// Freeze the clock with the given date and time, with the given kind of time.
 /// </summary>
 /// <param name="year">The frozen year</param>
 /// <param name="month">The frozen month</param>
 /// <param name="day">The frozen day</param>
 /// <param name="hour">The frozen hour</param>
 /// <param name="minute">The frozen minute</param>
 /// <param name="second">The frozen second</param>
 /// <param name="kind">The frozen time kind</param>
 public FreezeClockAttribute(int year,
                             int month,
                             int day,
                             int hour,
                             int minute,
                             int second,
                             DateTimeKind kind)
 {
     frozenDateTime = new DateTime(year, month, day, hour, minute, second, kind);
 }
        public DateTimeWithZone(DateTime dateTime, TimeZoneInfo timeZone, DateTimeKind kind = DateTimeKind.Utc)
        {
            dateTime = DateTime.SpecifyKind(dateTime, kind);

            utcDateTime = dateTime.Kind != DateTimeKind.Utc
                            ? TimeZoneInfo.ConvertTimeToUtc(dateTime, timeZone)
                            : dateTime;

            this.timeZone = timeZone;
        }
Exemple #21
0
        public static DateTime TicketToDateTime(this int ticket, DateTimeKind kind)
        {
            DateTime baseTime = new DateTime(1970, 1, 1);
            if (kind == DateTimeKind.Local)
                baseTime = baseTime.ToLocalTime();
            else if (kind == DateTimeKind.Utc)
                baseTime = baseTime.ToUniversalTime();

            return baseTime.AddSeconds(ticket);
        }
Exemple #22
0
 /// <summary>
 /// Converts a DateTime to local time (with special handling for MinValue and MaxValue).
 /// </summary>
 /// <param name="dateTime">A DateTime.</param>
 /// <param name="kind">A DateTimeKind.</param>
 /// <returns>The DateTime in local time.</returns>
 public static DateTime ToLocalTime(DateTime dateTime, DateTimeKind kind)
 {
     if (dateTime.Kind == kind) return dateTime;
     else
     {
         if (dateTime == DateTime.MinValue) return DateTime.SpecifyKind(DateTime.MinValue, kind);
         else if (dateTime == DateTime.MaxValue) return DateTime.SpecifyKind(DateTime.MaxValue, kind);
         else return DateTime.SpecifyKind(dateTime.ToLocalTime(), kind);
     }
 }
 /// <summary>
 /// DateTime을 Unix timestamp로 반환합니다.
 /// </summary>
 /// <param name="date">변환할 DateTime</param>
 /// <param name="includeMilliseconds">밀리초 단위인지 여부</param>
 /// <param name="kind">DateTime의 종류</param>
 /// <returns>변환된 Unix timestamp</returns>
 public static long ToUnixTime(this DateTime date, bool includeMilliseconds = true, DateTimeKind kind = DateTimeKind.Utc)
 {
     var epoch = new DateTime(1970, 1, 1, 0, 0, 0, kind);
     var diff = includeMilliseconds ? (date - epoch).TotalMilliseconds : (date - epoch).TotalSeconds;
     #if DNXCORE50
     return (long)diff;
     #else
     return (long)Math.Floor(diff);
     #endif
 }
Exemple #24
0
 /// <summary>
 /// Constructs the object used to interact with the SQLite core library
 /// using the UTF-8 text encoding.
 /// </summary>
 /// <param name="fmt">
 /// The DateTime format to be used when converting string values to a
 /// DateTime and binding DateTime parameters.
 /// </param>
 /// <param name="kind">
 /// The <see cref="DateTimeKind" /> to be used when creating DateTime
 /// values.
 /// </param>
 /// <param name="fmtString">
 /// The format string to be used when parsing and formatting DateTime
 /// values.
 /// </param>
 /// <param name="db">
 /// The native handle to be associated with the database connection.
 /// </param>
 /// <param name="fileName">
 /// The fully qualified file name associated with <paramref name="db" />.
 /// </param>
 /// <param name="ownHandle">
 /// Non-zero if the newly created object instance will need to dispose
 /// of <paramref name="db" /> when it is no longer needed.
 /// </param>
 internal SQLite3_UTF16(
     SQLiteDateFormats fmt,
     DateTimeKind kind,
     string fmtString,
     IntPtr db,
     string fileName,
     bool ownHandle
     )
     : base(fmt, kind, fmtString, db, fileName, ownHandle)
 {
 }
 public TimeParts(int hour, int minute, int second, int millisecond, DateTimeKind kind, TimeSpan offset) {
     if (kind == DateTimeKind.Utc && offset != TimeSpan.Zero) {
         throw new ArgumentOutOfRangeException(String.Format("The specified offset {0} does not match the specified kind {1}.", offset, kind));
     }
     _hour = hour;
     _minute = minute;
     _second = second;
     _millisecond = millisecond;
     _kind = kind;
     _offset = offset;
 }
Exemple #26
0
        /// <summary>
        /// Converts the String to a DateTime equivalent using the specified time zone
        /// </summary>
        /// <param name="s"></param>
        /// <param name="timeZone"></param>
        /// <param name="dateTimeKind"></param>
        /// <returns></returns>
        public static DateTime ToDateTime(string s, TzTimeZone timeZone, DateTimeKind dateTimeKind)
        {
            if (string.IsNullOrEmpty(s)) throw new ArgumentException(nameof(s));
            if (timeZone == null) throw new ArgumentNullException(nameof(timeZone));
            if (dateTimeKind == DateTimeKind.Unspecified) throw new ArgumentException(nameof(dateTimeKind));

            System.Text.RegularExpressions.Match m = dateRegex.Match(s);
            if (m.Success)
            {
                DateTime result = new DateTime(Convert.ToInt32(m.Groups["YEAR"].Value), Convert.ToInt32(m.Groups["MONTH"].Value),
                    Convert.ToInt32(m.Groups["DAY"].Value), Convert.ToInt32(m.Groups["HOUR"].Value), Convert.ToInt32(m.Groups["MINUTE"].Value),
                    Convert.ToInt32(m.Groups["SEC"].Value), DateTimeKind.Local);
                if (m.Groups["MS"].Success)
                {
                    result = result.AddMilliseconds(Convert.ToInt32(m.Groups["MS"]));
                }

                // Date is local, check return
                if (m.Groups["UTC"].Success)
                {
                    if (dateTimeKind == DateTimeKind.Utc)
                        return DateTime.SpecifyKind(result, DateTimeKind.Utc);
                    else
                        return timeZone.ToLocalTime(DateTime.SpecifyKind(result, DateTimeKind.Utc));
                }
                else {
                    // Date string is local, check offset
                    if (m.Groups["SGN"].Success)
                    {
                        // Translate in utc
                        if (m.Groups["SGN"].Value == "+")
                            result = result.AddHours(-Convert.ToInt32(m.Groups["SH"].Value)).AddMinutes(-Convert.ToInt32(m.Groups["SM"].Value));
                        else
                            result = result.AddHours(Convert.ToInt32(m.Groups["SH"].Value)).AddMinutes(Convert.ToInt32(m.Groups["SM"].Value));

                        if (dateTimeKind == DateTimeKind.Utc)
                            return DateTime.SpecifyKind(result, DateTimeKind.Utc);
                        else
                            return timeZone.ToLocalTime(DateTime.SpecifyKind(result, DateTimeKind.Utc));
                    }
                    else
                    {
                        // Zone unspecified, suppose to be local
                        if (dateTimeKind == DateTimeKind.Utc)
                            return timeZone.ToUniversalTime(result);
                        else
                            return result;
                    }
                }
            }

            throw new ArgumentException(string.Format("{0} is not a valid format", s));
        }
        /// <summary>
        /// Convierte los segundos desde el 1 de enero de 1970 a una fecha
        /// </summary>
        /// <param name="epochTimeInSeconds">Fecha</param>
        /// <returns></returns>
        public static DateTime ToDateTimeFromEpochInSeconds(this long epochTimeInSeconds, DateTimeKind dateTimeKind = DateTimeKind.Unspecified)
        {
            if (epochTimeInSeconds == 0)
                return new DateTime(1970, 1, 1, 0, 0, 0);

            var date = Epoch.AddSeconds(epochTimeInSeconds);

            if (dateTimeKind == DateTimeKind.Utc)
                return new DateTime(date.Ticks, dateTimeKind);

            return new DateTime(date.ToLocalTime().Ticks, dateTimeKind);
        }
 private ITimeService CreateTimeService(DateTimeKind kind, string format)
 {
     switch (kind)
     {
         case DateTimeKind.Local:
             return new LocalTimeService(format);
         case DateTimeKind.Utc:
             return new UtcTimeService(format);
         default:
             throw new NotSupportedException(string.Concat("The specified " + kind.GetType().Name +  " is not supported: ", kind));
     }
 }
		public DateTime GetCurrentTime(DateTimeKind kind)
		{
			switch (kind)
			{
				case DateTimeKind.Utc:
					return DateTime.UtcNow;
				case DateTimeKind.Local:
					return DateTime.Now;
				default:
					throw new ArgumentOutOfRangeException("kind");
			}
		}
        public __DateTime(long ticks, DateTimeKind kind)
        {
            //if ((ticks < 0L) || (ticks > 3155378975999999999L))
            //{
            //    throw new Exception("ArgumentOutOfRange_DateTimeBadTicks");
            //}

            var ms = (ticks - ticks_1970_1_1) / TicksPerMillisecond;

            this.InternalValue = new IDate(ms);
            this.Kind = kind;
        }
Exemple #31
0
 /// <summary>
 /// Converts the date and time to Coordinated Universal Time (UTC)
 /// </summary>
 /// <param name="dt">The date and time (respesents local system time or UTC time) to convert.</param>
 /// <param name="sourceDateTimeKind">The source datetimekind</param>
 /// <returns>A DateTime value that represents the Coordinated Universal Time (UTC) that corresponds to the dateTime parameter. The DateTime value's Kind property is always set to DateTimeKind.Utc.</returns>
 public virtual DateTime ConvertToUtcTime(DateTime dt, DateTimeKind sourceDateTimeKind)
 {
     dt = DateTime.SpecifyKind(dt, sourceDateTimeKind);
     return(TimeZoneInfo.ConvertTimeToUtc(dt, TimeZoneInfo.Utc));
 }
Exemple #32
0
 public static DateTime WithKind(this DateTime date, DateTimeKind kind)
 {
     return(new DateTime(date.Ticks, kind));
 }
Exemple #33
0
        internal static int WriteDateTimeString(char[] chars, int start, DateTime value, TimeSpan?offset, DateTimeKind kind, DateFormatHandling format)
        {
            int pos = start;

            if (format == DateFormatHandling.MicrosoftDateFormat)
            {
                TimeSpan o = offset ?? value.GetUtcOffset();

                long javaScriptTicks = ConvertDateTimeToJavaScriptTicks(value, o);

                @"\/Date(".CopyTo(0, chars, pos, 7);
                pos += 7;

                string ticksText = javaScriptTicks.ToString(CultureInfo.InvariantCulture);
                ticksText.CopyTo(0, chars, pos, ticksText.Length);
                pos += ticksText.Length;

                switch (kind)
                {
                case DateTimeKind.Unspecified:
                    if (value != DateTime.MaxValue && value != DateTime.MinValue)
                    {
                        pos = WriteDateTimeOffset(chars, pos, o, format);
                    }
                    break;

                case DateTimeKind.Local:
                    pos = WriteDateTimeOffset(chars, pos, o, format);
                    break;
                }

                @")\/".CopyTo(0, chars, pos, 3);
                pos += 3;
            }
            else
            {
                pos = WriteDefaultIsoDate(chars, pos, value);

                switch (kind)
                {
                case DateTimeKind.Local:
                    pos = WriteDateTimeOffset(chars, pos, offset ?? value.GetUtcOffset(), format);
                    break;

                case DateTimeKind.Utc:
                    chars[pos++] = 'Z';
                    break;
                }
            }

            return(pos);
        }
Exemple #34
0
 public VirtuosoDateTime(long ticks, DateTimeKind kind)
 {
     this.value = new DateTime(ticks, kind);
 }
Exemple #35
0
 /// <summary>
 /// Create a new DateRange object that represents the same period but is designated in either local or UTC time.
 /// </summary>
 /// <param name="range"></param>
 /// <param name="kind"></param>
 public static DateRange SpecifyKind(DateRange range, DateTimeKind kind)
 {
     return(new DateRange(range.start.ToUniversalTime(), range.finish.ToUniversalTime(), kind));
 }
Exemple #36
0
        //
        // Roundtrippable format. One of
        //
        //   012345678901234567890123456789012
        //   ---------------------------------
        //   2017-06-12T05:30:45.7680000-07:00
        //   2017-06-12T05:30:45.7680000Z           (Z is short for "+00:00" but also distinguishes DateTimeKind.Utc from DateTimeKind.Local)
        //   2017-06-12T05:30:45.7680000            (interpreted as local time wrt to current time zone)
        //
        private static bool TryParseDateTimeOffsetO(ReadOnlySpan <byte> source, out DateTimeOffset value, out int bytesConsumed, out DateTimeKind kind)
        {
            if (source.Length < 27)
            {
                value         = default;
                bytesConsumed = 0;
                kind          = default;
                return(false);
            }

            int year;

            {
                uint digit1 = source[0] - 48u; // '0'
                uint digit2 = source[1] - 48u; // '0'
                uint digit3 = source[2] - 48u; // '0'
                uint digit4 = source[3] - 48u; // '0'

                if (digit1 > 9 || digit2 > 9 || digit3 > 9 || digit4 > 9)
                {
                    value         = default;
                    bytesConsumed = 0;
                    kind          = default;
                    return(false);
                }

                year = (int)(digit1 * 1000 + digit2 * 100 + digit3 * 10 + digit4);
            }

            if (source[4] != Utf8Constants.Hyphen)
            {
                value         = default;
                bytesConsumed = 0;
                kind          = default;
                return(false);
            }

            int month;

            {
                uint digit1 = source[5] - 48u; // '0'
                uint digit2 = source[6] - 48u; // '0'

                if (digit1 > 9 || digit2 > 9)
                {
                    value         = default;
                    bytesConsumed = 0;
                    kind          = default;
                    return(false);
                }

                month = (int)(digit1 * 10 + digit2);
            }

            if (source[7] != Utf8Constants.Hyphen)
            {
                value         = default;
                bytesConsumed = 0;
                kind          = default;
                return(false);
            }

            int day;

            {
                uint digit1 = source[8] - 48u; // '0'
                uint digit2 = source[9] - 48u; // '0'

                if (digit1 > 9 || digit2 > 9)
                {
                    value         = default;
                    bytesConsumed = 0;
                    kind          = default;
                    return(false);
                }

                day = (int)(digit1 * 10 + digit2);
            }

            if (source[10] != 'T')
            {
                value         = default;
                bytesConsumed = 0;
                kind          = default;
                return(false);
            }

            int hour;

            {
                uint digit1 = source[11] - 48u; // '0'
                uint digit2 = source[12] - 48u; // '0'

                if (digit1 > 9 || digit2 > 9)
                {
                    value         = default;
                    bytesConsumed = 0;
                    kind          = default;
                    return(false);
                }

                hour = (int)(digit1 * 10 + digit2);
            }

            if (source[13] != Utf8Constants.Colon)
            {
                value         = default;
                bytesConsumed = 0;
                kind          = default;
                return(false);
            }

            int minute;

            {
                uint digit1 = source[14] - 48u; // '0'
                uint digit2 = source[15] - 48u; // '0'

                if (digit1 > 9 || digit2 > 9)
                {
                    value         = default;
                    bytesConsumed = 0;
                    kind          = default;
                    return(false);
                }

                minute = (int)(digit1 * 10 + digit2);
            }

            if (source[16] != Utf8Constants.Colon)
            {
                value         = default;
                bytesConsumed = 0;
                kind          = default;
                return(false);
            }

            int second;

            {
                uint digit1 = source[17] - 48u; // '0'
                uint digit2 = source[18] - 48u; // '0'

                if (digit1 > 9 || digit2 > 9)
                {
                    value         = default;
                    bytesConsumed = 0;
                    kind          = default;
                    return(false);
                }

                second = (int)(digit1 * 10 + digit2);
            }

            if (source[19] != Utf8Constants.Period)
            {
                value         = default;
                bytesConsumed = 0;
                kind          = default;
                return(false);
            }

            int fraction;
            {
                uint digit1 = source[20] - 48u; // '0'
                uint digit2 = source[21] - 48u; // '0'
                uint digit3 = source[22] - 48u; // '0'
                uint digit4 = source[23] - 48u; // '0'
                uint digit5 = source[24] - 48u; // '0'
                uint digit6 = source[25] - 48u; // '0'
                uint digit7 = source[26] - 48u; // '0'

                if (digit1 > 9 || digit2 > 9 || digit3 > 9 || digit4 > 9 || digit5 > 9 || digit6 > 9 || digit7 > 9)
                {
                    value         = default;
                    bytesConsumed = 0;
                    kind          = default;
                    return(false);
                }

                fraction = (int)(digit1 * 1000000 + digit2 * 100000 + digit3 * 10000 + digit4 * 1000 + digit5 * 100 + digit6 * 10 + digit7);
            }

            byte offsetChar = (source.Length <= 27) ? default : source[27];

                              if (offsetChar != 'Z' && offsetChar != Utf8Constants.Plus && offsetChar != Utf8Constants.Minus)
                              {
                                  if (!TryCreateDateTimeOffsetInterpretingDataAsLocalTime(year: year, month: month, day: day, hour: hour, minute: minute, second: second, fraction: fraction, out value))
                                  {
                                      value         = default;
                                      bytesConsumed = 0;
                                      kind          = default;
                                      return(false);
                                  }
                                  bytesConsumed = 27;
                                  kind          = DateTimeKind.Unspecified;
                                  return(true);
                              }

                              if (offsetChar == 'Z')
                              {
                                  // Same as specifying an offset of "+00:00", except that DateTime's Kind gets set to UTC rather than Local
                                  if (!TryCreateDateTimeOffset(year: year, month: month, day: day, hour: hour, minute: minute, second: second, fraction: fraction, offsetNegative: false, offsetHours: 0, offsetMinutes: 0, out value))
                                  {
                                      value         = default;
                                      bytesConsumed = 0;
                                      kind          = default;
                                      return(false);
                                  }

                                  bytesConsumed = 28;
                                  kind          = DateTimeKind.Utc;
                                  return(true);
                              }

                              Debug.Assert(offsetChar == Utf8Constants.Plus || offsetChar == Utf8Constants.Minus);
                              if (source.Length < 33)
                              {
                                  value         = default;
                                  bytesConsumed = 0;
                                  kind          = default;
                                  return(false);
                              }

                              int offsetHours;

                              {
                                  uint digit1 = source[28] - 48u; // '0'
                                  uint digit2 = source[29] - 48u; // '0'

                                  if (digit1 > 9 || digit2 > 9)
                                  {
                                      value         = default;
                                      bytesConsumed = 0;
                                      kind          = default;
                                      return(false);
                                  }

                                  offsetHours = (int)(digit1 * 10 + digit2);
                              }

                              if (source[30] != Utf8Constants.Colon)
                              {
                                  value         = default;
                                  bytesConsumed = 0;
                                  kind          = default;
                                  return(false);
                              }

                              int offsetMinutes;

                              {
                                  uint digit1 = source[31] - 48u; // '0'
                                  uint digit2 = source[32] - 48u; // '0'

                                  if (digit1 > 9 || digit2 > 9)
                                  {
                                      value         = default;
                                      bytesConsumed = 0;
                                      kind          = default;
                                      return(false);
                                  }

                                  offsetMinutes = (int)(digit1 * 10 + digit2);
                              }

                              if (!TryCreateDateTimeOffset(year: year, month: month, day: day, hour: hour, minute: minute, second: second, fraction: fraction, offsetNegative: offsetChar == Utf8Constants.Minus, offsetHours: offsetHours, offsetMinutes: offsetMinutes, out value))
                              {
                                  value         = default;
                                  bytesConsumed = 0;
                                  kind          = default;
                                  return(false);
                              }

                              bytesConsumed = 33;
                              kind          = DateTimeKind.Local;
                              return(true);
        }
 public static DateTime SpecifyKind(this DateTime dateTime, DateTimeKind kind)
 {
     DateTime.SpecifyKind(dateTime, kind);
     return(dateTime);
 }
 public DateTimeKindNormalisingDateTimeSqlDateType(ConstraintDefaultsConfiguration constraintDefaultsConfiguration, string typeName, bool nullable, DateTimeKind dateTimeKind, MethodInfo dataRecordGetMethod = null)
     : this(constraintDefaultsConfiguration, nullable ? typeof(DateTime?) : typeof(DateTime), typeName, dateTimeKind, dataRecordGetMethod)
 {
 }
 private static DateTime TimestampToDateTime(long timestamp, DateTimeKind kind)
 {
     return(new DateTime(1970, 1, 1, 0, 0, 0, 0, kind).AddSeconds(timestamp).ToLocalTime());
 }
Exemple #40
0
        public static DateTime?ParseManual(string dateTimeStr, DateTimeKind dateKind)
        {
            if (dateTimeStr == null || dateTimeStr.Length < ShortDateTimeFormat.Length)
            {
                return(null);
            }

            if (dateTimeStr.EndsWith(XsdUtcSuffix))
            {
                dateTimeStr = dateTimeStr.Substring(0, dateTimeStr.Length - 1);
                dateKind    = JsConfig.SkipDateTimeConversion ? DateTimeKind.Utc : dateKind;
            }

            var parts = dateTimeStr.Split('T');

            if (parts.Length == 1)
            {
                parts = dateTimeStr.SplitOnFirst(' ');
            }

            var    dateParts = parts[0].Split('-', '/');
            int    hh = 0, min = 0, ss = 0, ms = 0;
            double subMs            = 0;
            int    offsetMultiplier = 0;

            if (parts.Length == 1)
            {
                return(dateParts.Length == 3 && dateParts[2].Length == "YYYY".Length
                    ? new DateTime(int.Parse(dateParts[2]), int.Parse(dateParts[1]), int.Parse(dateParts[0]), 0, 0, 0, 0,
                                   dateKind)
                    : new DateTime(int.Parse(dateParts[0]), int.Parse(dateParts[1]), int.Parse(dateParts[2]), 0, 0, 0, 0,
                                   dateKind));
            }
            else if (parts.Length == 2)
            {
                var timeStringParts = parts[1].Split('+');
                if (timeStringParts.Length == 2)
                {
                    offsetMultiplier = -1;
                }
                else
                {
                    timeStringParts = parts[1].Split('-');
                    if (timeStringParts.Length == 2)
                    {
                        offsetMultiplier = 1;
                    }
                }

                var timeOffset = timeStringParts.Length == 2 ? timeStringParts[1] : null;
                var timeParts  = timeStringParts[0].Split(':');

                if (timeParts.Length == 3)
                {
                    int.TryParse(timeParts[0], out hh);
                    int.TryParse(timeParts[1], out min);

                    var secParts = timeParts[2].Split('.');
                    int.TryParse(secParts[0], out ss);
                    if (secParts.Length == 2)
                    {
                        var msStr = secParts[1].PadRight(3, '0');
                        ms = int.Parse(msStr.Substring(0, 3));

                        if (msStr.Length > 3)
                        {
                            var subMsStr = msStr.Substring(3);
                            subMs = double.Parse(subMsStr) / Math.Pow(10, subMsStr.Length);
                        }
                    }
                }

                var dateTime = new DateTime(int.Parse(dateParts[0]), int.Parse(dateParts[1]), int.Parse(dateParts[2]), hh, min,
                                            ss, ms, dateKind);
                if (subMs != 0)
                {
                    dateTime = dateTime.AddMilliseconds(subMs);
                }

                if (offsetMultiplier != 0 && timeOffset != null)
                {
                    timeParts = timeOffset.Split(':');
                    if (timeParts.Length == 2)
                    {
                        hh  = int.Parse(timeParts[0]);
                        min = int.Parse(timeParts[1]);
                    }
                    else
                    {
                        hh  = int.Parse(timeOffset.Substring(0, 2));
                        min = int.Parse(timeOffset.Substring(2));
                    }

                    dateTime = dateTime.AddHours(offsetMultiplier * hh);
                    dateTime = dateTime.AddMinutes(offsetMultiplier * min);
                }

                return(dateTime);
            }

            return(null);
        }
 public BsonBinaryWriter(BinaryWriter writer)
 {
     DateTimeKindHandling = DateTimeKind.Utc;
     _writer = writer;
 }
        internal static DateTime ParseJsonDateInDefaultFormat(string originalDateTimeValue)
        {
            // Dates are represented in JSON as "\/Date(number of ticks)\/".
            // The number of ticks is the number of milliseconds since January 1, 1970.

            string dateTimeValue;

            if (!string.IsNullOrEmpty(originalDateTimeValue))
            {
                dateTimeValue = originalDateTimeValue.Trim();
            }
            else
            {
                dateTimeValue = originalDateTimeValue;
            }

            if (string.IsNullOrEmpty(dateTimeValue) ||
                !dateTimeValue.StartsWith(JsonGlobals.DateTimeStartGuardReader, StringComparison.Ordinal) ||
                !dateTimeValue.EndsWith(JsonGlobals.DateTimeEndGuardReader, StringComparison.Ordinal))
            {
                throw new FormatException(SR.Format(SR.JsonInvalidDateTimeString, originalDateTimeValue, JsonGlobals.DateTimeStartGuardWriter, JsonGlobals.DateTimeEndGuardWriter));
            }

            string       ticksvalue = dateTimeValue.Substring(6, dateTimeValue.Length - 8);
            long         millisecondsSinceUnixEpoch;
            DateTimeKind dateTimeKind          = DateTimeKind.Utc;
            int          indexOfTimeZoneOffset = ticksvalue.IndexOf('+', 1);

            if (indexOfTimeZoneOffset == -1)
            {
                indexOfTimeZoneOffset = ticksvalue.IndexOf('-', 1);
            }

            if (indexOfTimeZoneOffset != -1)
            {
                dateTimeKind = DateTimeKind.Local;
                ticksvalue   = ticksvalue.Substring(0, indexOfTimeZoneOffset);
            }

            try
            {
                millisecondsSinceUnixEpoch = long.Parse(ticksvalue, CultureInfo.InvariantCulture);
            }
            catch (ArgumentException exception)
            {
                throw XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception);
            }
            catch (FormatException exception)
            {
                throw XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception);
            }
            catch (OverflowException exception)
            {
                throw XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception);
            }

            // Convert from # milliseconds since epoch to # of 100-nanosecond units, which is what DateTime understands
            long ticks = millisecondsSinceUnixEpoch * 10000 + JsonGlobals.unixEpochTicks;

            try
            {
                DateTime dateTime = new DateTime(ticks, DateTimeKind.Utc);
                switch (dateTimeKind)
                {
                case DateTimeKind.Local:
                    return(dateTime.ToLocalTime());

                case DateTimeKind.Unspecified:
                    return(DateTime.SpecifyKind(dateTime.ToLocalTime(), DateTimeKind.Unspecified));

                case DateTimeKind.Utc:
                default:
                    return(dateTime);
                }
            }
            catch (ArgumentException exception)
            {
                throw XmlExceptionHelper.CreateConversionException(ticksvalue, "DateTime", exception);
            }
        }
 public string ExpectedToStringDotnetFrameworkBehavior(long ticks, DateTimeKind kind)
 {
     return(new DateTime(ticks, kind).ToString("o"));
 }
Exemple #44
0
 internal static DateTime DecodeTimestamp(long value, DateTimeKind kind)
 => new(value * 10 + PostgresTimestampOffsetTicks, kind);
Exemple #45
0
 // IsValidTimeWithLeapSeconds is not expected to be called at all for now on non-Windows platforms
 internal static bool IsValidTimeWithLeapSeconds(int year, int month, int day, int hour, int minute, DateTimeKind kind) => false;
Exemple #46
0
        private static RubyTime /*!*/ CreateTime(int year, int month, int day, int hour, int minute, int second, int microsecond, DateTimeKind kind)
        {
            DateTime result = new DateTime(NormalizeYear(year), month, day, hour, minute, second == 60 ? 59 : second, 0, kind);

            if (second == 60)
            {
                result = result.AddSeconds(1);
            }
            return(new RubyTime(result.AddTicks(microsecond * 10)));
        }
Exemple #47
0
 public Date(int year, int month, int day, int hour, int minute, int second, int fraction, DateTimeKind kind,
             TimeSpan offset)
 {
     Year     = year;
     Month    = month;
     Day      = day;
     Hour     = hour;
     Minute   = minute;
     Second   = second;
     Fraction = fraction;
     Kind     = kind;
     Offset   = offset;
 }
Exemple #48
0
        public static int WriteDateTimeString(char[] chars, int start, DateTime value, TimeSpan?offset, DateTimeKind kind, DateFormatHandling format)
        {
            int num2;

            if (format == DateFormatHandling.MicrosoftDateFormat)
            {
                TimeSpan offset2 = offset ?? value.GetUtcOffset();
                long     num     = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(value, offset2);
                "\\/Date(".CopyTo(0, chars, start, 7);
                num2 = start + 7;
                string text = num.ToString(CultureInfo.InvariantCulture);
                text.CopyTo(0, chars, num2, text.Length);
                num2 += text.Length;
                switch (kind)
                {
                case DateTimeKind.Unspecified:
                    if (value != DateTime.MaxValue && value != DateTime.MinValue)
                    {
                        num2 = DateTimeUtils.WriteDateTimeOffset(chars, num2, offset2, format);
                    }
                    break;

                case DateTimeKind.Local:
                    num2 = DateTimeUtils.WriteDateTimeOffset(chars, num2, offset2, format);
                    break;
                }
                ")\\/".CopyTo(0, chars, num2, 3);
                num2 += 3;
            }
            else
            {
                num2 = DateTimeUtils.WriteDefaultIsoDate(chars, start, value);
                switch (kind)
                {
                case DateTimeKind.Utc:
                    chars[num2++] = 'Z';
                    break;

                case DateTimeKind.Local:
                    num2 = DateTimeUtils.WriteDateTimeOffset(chars, num2, offset ?? value.GetUtcOffset(), format);
                    break;
                }
            }
            return(num2);
        }
Exemple #49
0
        private static void VerifyDateTime(DateTime dateTime, int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind kind)
        {
            Assert.Equal(year, dateTime.Year);
            Assert.Equal(month, dateTime.Month);
            Assert.Equal(day, dateTime.Day);
            Assert.Equal(hour, dateTime.Hour);
            Assert.Equal(minute, dateTime.Minute);
            Assert.Equal(second, dateTime.Second);
            Assert.Equal(millisecond, dateTime.Millisecond);

            Assert.Equal(kind, dateTime.Kind);
        }
Exemple #50
0
 public VirtuosoDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, DateTimeKind kind)
 {
     this.value = new DateTime(year, month, day, hour, minute, second, millisecond, calendar, kind);
 }
Exemple #51
0
 static void CompareDates(DateTime expected, DateTime actual, DateTimeKind expectedKind, string caption)
 {
     Assert.AreEqual(expectedKind, actual.Kind, caption);
     Assert.AreEqual(expected.Date, actual.Date, caption);
     Assert.AreEqual(expected.TimeOfDay, actual.TimeOfDay, caption);
 }
Exemple #52
0
 public static XmlDateTimeSerializationMode ToSerializationMode(DateTimeKind kind)
 {
     return(Api.ToSerializationMode(kind));
 }
 public static DateTime SpecifyKindIfUnspecified(DateTime dateTime, DateTimeKind kind)
 {
     return(dateTime.Kind == DateTimeKind.Unspecified ? DateTime.SpecifyKind(dateTime, kind) : dateTime);
 }
        /// <summary>
        /// Converts a date time to an ISO 8601 formatted string, using the DateTimeKind
        /// to format the timezone appropriately. Kind defaults to Local.
        ///
        /// Example: 2007-08-13T16:48:01+0300
        /// </summary>
        public static string ToISO8601(this DateTime date, DateTimeKind kind = DateTimeKind.Local)
        {
            var kinded = new DateTime(date.Ticks, kind);

            return(kinded.ToString(Formats.ISO_8601));
        }
Exemple #55
0
 public static string ToDateTimeFormat(DateTimeKind kind)
 {
     return(Api.ToDateTimeFormat(kind));
 }
Exemple #56
0
        public static void VerifyExpiration_LocalTime(DateTime verificationTime, bool shouldBeValid, DateTimeKind kind)
        {
            using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
                using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
                    using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
                        using (var chainHolder = new ChainHolder())
                        {
                            X509Chain chain = chainHolder.Chain;

                            chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer);
                            chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);

                            // Ignore anything except NotTimeValid
                            chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags & ~X509VerificationFlags.IgnoreNotTimeValid;
                            chain.ChainPolicy.RevocationMode    = X509RevocationMode.NoCheck;
                            chain.ChainPolicy.VerificationTime  = verificationTime;

                            bool builtSuccessfully = chain.Build(microsoftDotCom);

                            Assert.Equal(shouldBeValid, builtSuccessfully);

                            // If we failed to build the chain, ensure that NotTimeValid is one of the reasons.
                            if (!shouldBeValid)
                            {
                                Assert.Contains(chain.ChainStatus, s => s.Status == X509ChainStatusFlags.NotTimeValid);
                            }
                        }
        }
Exemple #57
0
 public RubyTime(long ticks, DateTimeKind kind)
     : this(new DateTime(ticks, kind))
 {
 }
Exemple #58
0
        private static bool TryParseDateMicrosoft(string text, DateParseHandling dateParseHandling, DateTimeZoneHandling dateTimeZoneHandling, out object dt)
        {
            string       value = text.Substring(6, text.Length - 8);
            DateTimeKind kind  = DateTimeKind.Utc;

            int index = value.IndexOf('+', 1);

            if (index == -1)
            {
                index = value.IndexOf('-', 1);
            }

#if !NET20
            TimeSpan offset = TimeSpan.Zero;
#endif

            if (index != -1)
            {
                kind = DateTimeKind.Local;
#if !NET20
                offset = ReadOffset(value.Substring(index));
#endif
                value = value.Substring(0, index);
            }

            long javaScriptTicks;
            if (!long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out javaScriptTicks))
            {
                dt = null;
                return(false);
            }

            DateTime utcDateTime = ConvertJavaScriptTicksToDateTime(javaScriptTicks);

#if !NET20
            if (dateParseHandling == DateParseHandling.DateTimeOffset)
            {
                dt = new DateTimeOffset(utcDateTime.Add(offset).Ticks, offset);
                return(true);
            }
#endif

            DateTime dateTime;
            switch (kind)
            {
            case DateTimeKind.Unspecified:
                dateTime = DateTime.SpecifyKind(utcDateTime.ToLocalTime(), DateTimeKind.Unspecified);
                break;

            case DateTimeKind.Local:
                dateTime = utcDateTime.ToLocalTime();
                break;

            default:
                dateTime = utcDateTime;
                break;
            }

            dt = EnsureDateTime(dateTime, dateTimeZoneHandling);
            return(true);
        }
Exemple #59
0
        internal static void WriteDateTimeString(TextWriter writer, DateTime value, TimeSpan offset, DateTimeKind kind)
        {
            long javaScriptTicks = ConvertDateTimeToJavaScriptTicks(value, offset);

            writer.Write(@"""\/Date(");
            writer.Write(javaScriptTicks);

            switch (kind)
            {
            case DateTimeKind.Local:
            case DateTimeKind.Unspecified:
                writer.Write((offset.Ticks >= 0L) ? "+" : "-");

                int absHours = Math.Abs(offset.Hours);
                if (absHours < 10)
                {
                    writer.Write(0);
                }
                writer.Write(absHours);
                int absMinutes = Math.Abs(offset.Minutes);
                if (absMinutes < 10)
                {
                    writer.Write(0);
                }
                writer.Write(absMinutes);
                break;
            }

            writer.Write(@")\/""");
        }
 public DateTimeKindNormalisingDateTimeSqlDateType(ConstraintDefaultsConfiguration constraintDefaultsConfiguration, Type type, string typeName, DateTimeKind dateTimeKind, MethodInfo dataRecordGetMethod = null)
     : base(constraintDefaultsConfiguration, type, typeName, dataRecordGetMethod ?? DataRecordMethods.GetMethod(nameof(IDataRecord.GetDateTime)))
 {
     this.dateTimeKind      = dateTimeKind;
     this.specifyKindMethod = type.IsNullableType() ? specifyKindIfUnspecifiedMethodNullable : specifyKindIfUnspecifiedMethod;
 }