当前位置: 首页>>代码示例>>C#>>正文


C# DateTime.ToLocalTime方法代码示例

本文整理汇总了C#中DateTime.ToLocalTime方法的典型用法代码示例。如果您正苦于以下问题:C# DateTime.ToLocalTime方法的具体用法?C# DateTime.ToLocalTime怎么用?C# DateTime.ToLocalTime使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在DateTime的用法示例。


在下文中一共展示了DateTime.ToLocalTime方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: SettingUpdatesProperties

        public void SettingUpdatesProperties()
        {
            FileInfo testFile = new FileInfo(GetTestFilePath());
            testFile.Create().Dispose();

            Assert.All(TimeFunctions(requiresRoundtripping: true), (tuple) =>
            {
                DateTime dt = new DateTime(2014, 12, 1, 12, 0, 0, tuple.Item3);
                tuple.Item1(testFile, dt);
                var result = tuple.Item2(testFile);
                Assert.Equal(dt, result);
                Assert.Equal(dt.ToLocalTime(), result.ToLocalTime());

                // File and Directory UTC APIs treat a DateTimeKind.Unspecified as UTC whereas
                // ToUniversalTime treats it as local.
                if (tuple.Item3 == DateTimeKind.Unspecified)
                {
                    Assert.Equal(dt, result.ToUniversalTime());
                }
                else
                {
                    Assert.Equal(dt.ToUniversalTime(), result.ToUniversalTime());
                }
            });
        }
开发者ID:ChuangYang,项目名称:corefx,代码行数:25,代码来源:GetSetTimes.cs

示例2: Set

		public override void Set (string key, object entry, DateTime utcExpiry)
		{
			Cache cache = HttpRuntime.InternalCache;
			string cacheKey = CACHE_PREFIX + key;
			object oldObject = cache.Get (cacheKey);

			if (oldObject != null)
				cache.Remove (cacheKey);
			
			cache.Add (cacheKey, entry, null, utcExpiry.ToLocalTime (), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
		}
开发者ID:nlhepler,项目名称:mono,代码行数:11,代码来源:InMemoryOutputCacheProvider.cs

示例3: SettingUpdatesProperties

        public void SettingUpdatesProperties()
        {
            DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());

            Assert.All(TimeFunctions(requiresRoundtripping: true), (tuple) =>
            {
                DateTime dt = new DateTime(2014, 12, 1, 12, 0, 0, tuple.Item3);
                tuple.Item1(testDir, dt);
                var result = tuple.Item2(testDir);
                Assert.Equal(dt, result);
                Assert.Equal(dt.ToLocalTime(), result.ToLocalTime());
                Assert.Equal(dt.ToUniversalTime(), result.ToUniversalTime());
            });
        }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:14,代码来源:GetSetTimes.cs

示例4: SettingUpdatesProperties

        public void SettingUpdatesProperties()
        {
            FileInfo testFile = new FileInfo(GetTestFilePath());
            testFile.Create().Dispose();

            Assert.All(TimeFunctions(), (tuple) =>
            {
                DateTime dt = new DateTime(2014, 12, 1, 12, 0, 0, tuple.Item3);
                tuple.Item1(testFile.FullName, dt);
                var result = tuple.Item2(testFile.FullName);
                Assert.Equal(dt, result);
                Assert.Equal(dt.ToLocalTime(), result.ToLocalTime());
                Assert.Equal(dt.ToUniversalTime(), result.ToUniversalTime());
            });
        }
开发者ID:jmhardison,项目名称:corefx,代码行数:15,代码来源:GetSetTimes.cs

示例5: ParseHttpDate


//.........这里部分代码省略.........
            int year;
            int month;
            int day;
            int hour;
            int minute;
            int second;
            int millisecond;

            millisecond =  0;

            if (fIsANSIDateFormat) {
                day    = rgdwDateParseResults[DATE_ANSI_INDEX_DAY];
                month  = rgdwDateParseResults[DATE_ANSI_INDEX_MONTH];
                hour   = rgdwDateParseResults[DATE_ANSI_INDEX_HRS];
                minute = rgdwDateParseResults[DATE_ANSI_INDEX_MINS];
                second = rgdwDateParseResults[DATE_ANSI_INDEX_SECS];
                if (iLastLettered != DATE_ANSI_INDEX_YEAR) {
                    year   = rgdwDateParseResults[DATE_ANSI_INDEX_YEAR];
                }
                else {
                    // This is a fix to get around toString/toGMTstring (where the timezone is
                    // appended at the end. (See above)
                    year   = rgdwDateParseResults[DATE_INDEX_TZ];
                }
            }
            else {
                day    = rgdwDateParseResults[DATE_1123_INDEX_DAY];
                month  = rgdwDateParseResults[DATE_1123_INDEX_MONTH];
                year   = rgdwDateParseResults[DATE_1123_INDEX_YEAR];
                hour   = rgdwDateParseResults[DATE_1123_INDEX_HRS];
                minute = rgdwDateParseResults[DATE_1123_INDEX_MINS];
                second = rgdwDateParseResults[DATE_1123_INDEX_SECS];
            }

            //
            // Normalize the year, 90 == 1990, handle the year 2000, 02 == 2002
            //  This is Year 2000 handling folks!!!  We get this wrong and
            //  we all look bad.
            //

            if (year < 100) {
                year += ((year < 80) ? 2000 : 1900);
            }

            //
            // if we got misformed time, then plug in the current time
            // !lpszHrs || !lpszMins || !lpszSec
            //

            if ((i < 4)
                || (day > 31)
                || (hour > 23)
                || (minute > 59)
                || (second > 59)) {
                fRet = false;
                goto quit;
            }

            //
            // Now do the DateTime conversion
            //

            dtOut = new DateTime (year, month, day, hour, minute, second, millisecond);

            //
            // we want the system time to be accurate. This is _suhlow_
            // The time passed in is in the local time zone; we have to convert this into GMT.
            //

            if (iLastLettered==DATE_ANSI_INDEX_YEAR) {
                // this should be an unusual case.
                dtOut = dtOut.ToUniversalTime();
            }

            //
            // If we have an Offset to another Time Zone
            //   then convert to appropriate GMT time
            //

            if ((i > DATE_INDEX_TZ &&
                 rgdwDateParseResults[DATE_INDEX_TZ] != DATE_TOKEN_GMT)) {

                //
                // if we received +/-nnnn as offset (hhmm), modify the output FILETIME
                //

                double offset;

                offset = (double) rgdwDateParseResults[DATE_INDEX_TZ];
                dtOut.AddHours(offset);
            }

            // In the end, we leave it all in LocalTime

            dtOut = dtOut.ToLocalTime();

            quit:

            return fRet;
        }
开发者ID:uQr,项目名称:referencesource,代码行数:101,代码来源:_HTTPDateParse.cs

示例6: SwitchToLocalTime

        private static DateTime SwitchToLocalTime(DateTime value)
        {
            switch (value.Kind)
            {
                case DateTimeKind.Local:
                    return value;

                case DateTimeKind.Unspecified:
                    return new DateTime(value.Ticks, DateTimeKind.Local);

                case DateTimeKind.Utc:
                    return value.ToLocalTime();
            }
            return value;
        }
开发者ID:shiftkey-tester,项目名称:corefx,代码行数:15,代码来源:XmlConvert.cs

示例7: GetLastModifiedFrom213Response

 /// <summary>
 ///    <para>Parses a response string for last modified time</para>
 /// </summary>
 private DateTime GetLastModifiedFrom213Response(string str)
 {
     DateTime dateTime = _lastModified;
     string[] parsedList = str.Split(new char[] { ' ', '.' });
     if (parsedList.Length < 2)
     {
         return dateTime;
     }
     string dateTimeLine = parsedList[1];
     if (dateTimeLine.Length < 14)
     {
         return dateTime;
     }
     int year = Convert.ToInt32(dateTimeLine.Substring(0, 4), NumberFormatInfo.InvariantInfo);
     int month = Convert.ToInt16(dateTimeLine.Substring(4, 2), NumberFormatInfo.InvariantInfo);
     int day = Convert.ToInt16(dateTimeLine.Substring(6, 2), NumberFormatInfo.InvariantInfo);
     int hour = Convert.ToInt16(dateTimeLine.Substring(8, 2), NumberFormatInfo.InvariantInfo);
     int minute = Convert.ToInt16(dateTimeLine.Substring(10, 2), NumberFormatInfo.InvariantInfo);
     int second = Convert.ToInt16(dateTimeLine.Substring(12, 2), NumberFormatInfo.InvariantInfo);
     int millisecond = 0;
     if (parsedList.Length > 2)
     {
         millisecond = Convert.ToInt16(parsedList[2], NumberFormatInfo.InvariantInfo);
     }
     try
     {
         dateTime = new DateTime(year, month, day, hour, minute, second, millisecond);
         dateTime = dateTime.ToLocalTime(); // must be handled in local time
     }
     catch (ArgumentOutOfRangeException)
     {
     }
     catch (ArgumentException)
     {
     }
     return dateTime;
 }
开发者ID:dotnet,项目名称:corefx,代码行数:40,代码来源:FtpControlStream.cs

示例8: WriteDateTimeInDefaultFormat

        private void WriteDateTimeInDefaultFormat(DateTime value)
        {
            // ToUniversalTime() truncates dates to DateTime.MaxValue or DateTime.MinValue instead of throwing
            // This will break round-tripping of these dates (see 
            if (value.Kind != DateTimeKind.Utc)
            {
                //long tickCount = value.Ticks - TimeZone.CurrentTimeZone.GetUtcOffset(value).Ticks;
                long tickCount = value.Ticks - TimeZoneInfo.Local.GetUtcOffset(value).Ticks;
                if ((tickCount > DateTime.MaxValue.Ticks) || (tickCount < DateTime.MinValue.Ticks))
                {
                    throw XmlObjectSerializer.CreateSerializationException(SR.JsonDateTimeOutOfRange, new ArgumentOutOfRangeException("value"));
                }
            }

            writer.WriteString(JsonGlobals.DateTimeStartGuardReader);
            writer.WriteValue((value.ToUniversalTime().Ticks - JsonGlobals.unixEpochTicks) / 10000);

            switch (value.Kind)
            {
                case DateTimeKind.Unspecified:
                case DateTimeKind.Local:
                    // +"zzzz";
                    //TimeSpan ts = TimeZone.CurrentTimeZone.GetUtcOffset(value.ToLocalTime());
                    TimeSpan ts = TimeZoneInfo.Local.GetUtcOffset(value.ToLocalTime());
                    if (ts.Ticks < 0)
                    {
                        writer.WriteString("-");
                    }
                    else
                    {
                        writer.WriteString("+");
                    }
                    int hours = Math.Abs(ts.Hours);
                    writer.WriteString((hours < 10) ? "0" + hours : hours.ToString(CultureInfo.InvariantCulture));
                    int minutes = Math.Abs(ts.Minutes);
                    writer.WriteString((minutes < 10) ? "0" + minutes : minutes.ToString(CultureInfo.InvariantCulture));
                    break;
                case DateTimeKind.Utc:
                    break;
            }
            writer.WriteString(JsonGlobals.DateTimeEndGuardReader);
        }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:42,代码来源:JsonWriterDelegator.cs

示例9: SetLastWriteTimeUtc

		public static void SetLastWriteTimeUtc (string path, DateTime lastWriteTimeUtc)
		{
			SetLastWriteTime (path, lastWriteTimeUtc.ToLocalTime ());
		}
开发者ID:REALTOBIZ,项目名称:mono,代码行数:4,代码来源:Directory.cs

示例10: SetCreationTimeUtc

		public static void SetCreationTimeUtc (string path, DateTime creationTimeUtc)
		{
			SetCreationTime (path, creationTimeUtc.ToLocalTime ());
		}
开发者ID:REALTOBIZ,项目名称:mono,代码行数:4,代码来源:Directory.cs

示例11: BuiltTime

            private static DateTime BuiltTime()
            {
                string filePath = System.Reflection.Assembly.GetCallingAssembly().Location;
                const int c_PeHeaderOffset = 60;
                const int c_LinkerTimestampOffset = 8;
                byte[] b = new byte[2048];
                System.IO.Stream s = null;

                try
                {
                    s = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                    s.Read(b, 0, 2048);
                }
                finally
                {
                    if (s != null)
                    {
                        s.Close();
                    }
                }

                int i = System.BitConverter.ToInt32(b, c_PeHeaderOffset);
                int secondsSince1970 = System.BitConverter.ToInt32(b, i + c_LinkerTimestampOffset);
                DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                dt = dt.AddSeconds(secondsSince1970);
                dt = dt.ToLocalTime();
                return dt;
            }
开发者ID:Teknoman117,项目名称:Kopernicus,代码行数:28,代码来源:Version.cs

示例12: DeserializeStringIntoDateTime

        private object DeserializeStringIntoDateTime()
        {
            string dateTimeValue = DeserializeString();
            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 = Int64.Parse(ticksvalue, NumberStyles.Integer, CultureInfo.InvariantCulture);
            }
            catch (ArgumentException exception)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception));
            }
            catch (FormatException exception)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception));
            }
            catch (OverflowException exception)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(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:
                        dateTime = dateTime.ToLocalTime();
                        break;
                    case DateTimeKind.Unspecified:
                        dateTime = DateTime.SpecifyKind(dateTime.ToLocalTime(), DateTimeKind.Unspecified);
                        break;
                    case DateTimeKind.Utc:
                    default:
                        break;
                }

                // This string could be serialized from DateTime or String, keeping both until DataContract information is available
                return Tuple.Create<DateTime, string>(dateTime, dateTimeValue);
            }
            catch (ArgumentException exception)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(ticksvalue, "DateTime", exception));
            }
        }
开发者ID:eerhardt,项目名称:corefx,代码行数:63,代码来源:JavaScriptObjectDeserializer.cs

示例13: FromUtc

        internal static FormsAuthenticationTicket FromUtc(int version, String name, DateTime issueDateUtc, DateTime expirationUtc, bool isPersistent, String userData, String cookiePath) {
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(version, name, issueDateUtc.ToLocalTime(), expirationUtc.ToLocalTime(), isPersistent, userData, cookiePath);

            ticket._IssueDateUtcHasValue = true;
            ticket._IssueDateUtc = issueDateUtc;
            ticket._ExpirationUtcHasValue = true;
            ticket._ExpirationUtc = expirationUtc;

            return ticket;
        }
开发者ID:iskiselev,项目名称:JSIL.NetFramework,代码行数:10,代码来源:FormsAuthenticationTicket.cs

示例14: WriteDateTimeInDefaultFormat

        private void WriteDateTimeInDefaultFormat(DateTime value)
        {
            // ToUniversalTime() truncates dates to DateTime.MaxValue or DateTime.MinValue instead of throwing
            // This will break round-tripping of these dates (see 
            if (value.Kind != DateTimeKind.Utc)
            {
                // Fetching the UtcOffset is expensive so we need to avoid it if possible. We can do a fast
                // bounds check to decide if the more expensive bounds check is needed. The result from 
                // TimeZoneInfo.Local.GetUtcOffset(value) is bounded to +/- 24 hours. If 
                // (DateTime.MinValue + 24 hours) < value < (DateTime.MaxValue – 24 hours), then we don't need
                // to check using the the real UtcOffset as it doesn't matter what the offset is, it can't cause
                // an overflow/underflow condition.
                
                // Pre-calculated value of DateTime.MinValue.AddDays(1.0).Ticks;
                long lowBound = 0xC92A69C000;
                // Pre-calculated value of DateTime.MaxValue.AddDays(-1.0).Ticks;
                long highBound = 0x2BCA27ACC9CD7FFF;

                long tickCount = value.Ticks;
                if (lowBound > tickCount || highBound < tickCount) // We could potentially under/over flow
                {
                    tickCount = tickCount - TimeZoneInfo.Local.GetUtcOffset(value).Ticks;
                    if ((tickCount > DateTime.MaxValue.Ticks) || (tickCount < DateTime.MinValue.Ticks))
                    {
                        throw XmlObjectSerializer.CreateSerializationException(SR.JsonDateTimeOutOfRange, new ArgumentOutOfRangeException(nameof(value)));
                    }
                }
            }

            writer.WriteString(JsonGlobals.DateTimeStartGuardReader);
            writer.WriteValue((value.ToUniversalTime().Ticks - JsonGlobals.unixEpochTicks) / 10000);

            switch (value.Kind)
            {
                case DateTimeKind.Unspecified:
                case DateTimeKind.Local:
                    // +"zzzz";
                    //TimeSpan ts = TimeZone.CurrentTimeZone.GetUtcOffset(value.ToLocalTime());
                    TimeSpan ts = TimeZoneInfo.Local.GetUtcOffset(value.ToLocalTime());
                    writer.WriteString(string.Format(CultureInfo.InvariantCulture, "{0:+00;-00}{1:00;00}", ts.Hours, ts.Minutes));
                    break;
                case DateTimeKind.Utc:
                    break;
            }
            writer.WriteString(JsonGlobals.DateTimeEndGuardReader);
        }
开发者ID:ESgarbi,项目名称:corefx,代码行数:46,代码来源:JsonWriterDelegator.cs

示例15: Add

		public override object Add (string key, object entry, DateTime utcExpiry)
		{
			return HttpRuntime.InternalCache.Add (CACHE_PREFIX + key, entry, null, utcExpiry.ToLocalTime (), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
		}
开发者ID:nlhepler,项目名称:mono,代码行数:4,代码来源:InMemoryOutputCacheProvider.cs


注:本文中的DateTime.ToLocalTime方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。