• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# TimeSpan类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中TimeSpan的典型用法代码示例。如果您正苦于以下问题:C# TimeSpan类的具体用法?C# TimeSpan怎么用?C# TimeSpan使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



TimeSpan类属于命名空间,在下文中一共展示了TimeSpan类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: SetTime

 /// <summary>
 /// 	Sets the time on the specified DateTime value using the specified time zone.
 /// </summary>
 /// <param name = "datetimeOff">The base date.</param>
 /// <param name = "timespan">The TimeSpan to be applied.</param>
 /// <param name = "localTimeZone">The local time zone.</param>
 /// <returns>/// The DateTimeOffset including the new time value/// </returns>
 public static DateTimeOffset SetTime(this DateTimeOffset datetimeOff, TimeSpan timespan,
                                      TimeZoneInfo localTimeZone)
 {
     var localDate = datetimeOff.ToLocalDateTime(localTimeZone);
     localDate.SetTime(timespan);
     return localDate.ToDateTimeOffset(localTimeZone);
 }
开发者ID:erashid,项目名称:Extensions,代码行数:14,代码来源:DateTimeOffsetExtension.cs


示例2: Reglage

 public Reglage(ReglageViewModel rvm){
     Id = rvm.IdReglage;
     Duree = new TimeSpan(rvm.Duree, 0, 0, 0);
     Lumiere = Math.Round(rvm.Lumiere, 2);
     TemperatureInterieur = Math.Round(rvm.TemperatureInterieur, 2);
     Humidite = Math.Round(rvm.Humidite, 2);
 }
开发者ID:NoxXtrem,项目名称:Projet_Serre,代码行数:7,代码来源:Reglage.cs


示例3: RetrieveFileData

 private void RetrieveFileData(HttpContext context, string filePath, string container)
 {
     MediaFileModel resultModel = new MediaFileModel();
     // only send request to imageprocessor if querystring exists; can exclude other parameters if needed
     if (context.Request.RawUrl.Contains("?"))
     {
         resultModel = MediaHelper.GetMediaFile(filePath, container, context.Request.RawUrl);
     }
     else
     {
         resultModel = MediaHelper.GetMediaFile(filePath, container);
     }
     if (resultModel.RedirectToAzureStorage)
     {
         context.Response.Redirect(filePath.Replace($"/{container}", $"{ConfigurationManager.AppSettings["BlobStorage"]}/{container}"), true);
     }
     var myTimeSpan = new TimeSpan(7, 0, 0, 0);
     context.Response.Cache.SetCacheability(HttpCacheability.Public);
     context.Response.Cache.SetValidUntilExpires(true);
     context.Response.Cache.SetMaxAge(myTimeSpan);
     context.Response.Cache.SetLastModified(resultModel.LastModifiedDate);
     context.Response.Cache.SetETag(resultModel.ETag.Replace("\\\"", ""));
     context.Response.AddHeader("Content-MD5", resultModel.ContentMd5);
     context.Response.ContentType = resultModel.ContentType;
     // replicate properties returned by blob storage
     context.Response.AddHeader("Server", "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0");
     context.Response.AddHeader("x-ms-request-id", Guid.NewGuid().ToString());
     context.Response.AddHeader("x-ms-version", "2009-09-19");
     context.Response.AddHeader("x-ms-lease-status", "unlocked");
     context.Response.AddHeader("x-ms-blob-type", "BlockBlob");
     context.Response.OutputStream.Write(resultModel.ImageData, 0, resultModel.ImageData.Length);
     context.Response.AddHeader("Content-Length", resultModel.ImageData.Length.ToString());
     context.Response.Flush();
     context.Response.End();
 }
开发者ID:tstahnke,项目名称:umbraco-azure-cdn,代码行数:35,代码来源:MediaModule.cs


示例4: UnixTicks

 /// <summary>
 /// Datetime转Json时间,datetime - 1970.1.1
 /// </summary>
 /// <param name="dt"></param>
 /// <returns></returns>
 public static int UnixTicks(DateTime dt)
 {
     DateTime d1 = new DateTime(1970, 1, 1);
     DateTime d2 = dt.ToUniversalTime();
     TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
     return (int)ts.TotalSeconds;
 }
开发者ID:liguobao,项目名称:kzhihu,代码行数:12,代码来源:CommonHelper.cs


示例5: StartCountdown

 public void StartCountdown(int hours, int minutes, int seconds, Action callback)
 {
     countFrom = new TimeSpan(hours, minutes, seconds);
     stopWatch = new Stopwatch();
     cb = callback;
     stopWatch.Start();
 }
开发者ID:Reintjuu,项目名称:FastType,代码行数:7,代码来源:Countdown.cs


示例6: GetPositionAtUT

        /// <summary>
        ///   Calculates the position of this vessel at some future universal timestamp,
        ///   taking into account all currently predicted SOI transition patches, and also
        ///   assuming that all the planned maneuver nodes will actually be executed precisely
        ///   as planned.  Note that this cannot "see" into the future any farther than the
        ///   KSP orbit patches setting allows for.
        /// </summary>
        /// <param name="timeStamp">The time to predict for.  Although the intention is to
        ///   predict for a future time, it could be used to predict for a past time.</param>
        /// <returns>The position as a user-readable Vector in Shared.Vessel-origin raw rotation coordinates.</returns>
        override public Vector GetPositionAtUT(TimeSpan timeStamp)
        {
            string blockingTech;
            if (!Career.CanMakeNodes(out blockingTech))
                throw new KOSLowTechException("use POSITIONAT on a vessel", blockingTech);

            double desiredUT = timeStamp.ToUnixStyleTime();

            Orbit patch = GetOrbitAtUT(desiredUT);
            Vector3d pos = patch.getPositionAtUT(desiredUT);

            // This is an ugly workaround to fix what is probably a bug in KSP's API:
            // If looking at a future orbit patch around a child body of the current body, then
            // the various get{Thingy}AtUT() methods return numbers calculated incorrectly as
            // if the child body was going to remain stationary where it is now, rather than
            // taking into account where it will be later when the intercept happens.
            // This corrects for that case:
            if (Utils.BodyOrbitsBody(patch.referenceBody, Vessel.orbit.referenceBody))
            {
                Vector3d futureSOIPosNow = patch.referenceBody.position;
                Vector3d futureSOIPosLater = patch.referenceBody.getPositionAtUT(desiredUT);
                Vector3d offset = futureSOIPosLater - futureSOIPosNow;
                pos = pos + offset;
            }

            return new Vector(pos - Shared.Vessel.findWorldCenterOfMass()); // Convert to ship-centered frame.
        }
开发者ID:Whitecaribou,项目名称:KOS,代码行数:37,代码来源:VesselTarget.cs


示例7: RetryConditionHeaderValue

		public RetryConditionHeaderValue (TimeSpan delta)
		{
			if (delta.TotalSeconds > uint.MaxValue)
				throw new ArgumentOutOfRangeException ("delta");

			Delta = delta;
		}
开发者ID:nlhepler,项目名称:mono,代码行数:7,代码来源:RetryConditionHeaderValue.cs


示例8: EnterAsync

        public bool EnterAsync(TimeSpan timeout, FastAsyncCallback callback, object state)
        {
            Fx.Assert(callback != null, "must have a non-null call back for async purposes");

            AsyncWaitHandle waiter = null;

            lock (this.ThisLock)
            {
                if (this.aborted)
                {
                    throw Fx.Exception.AsError(CreateObjectAbortedException());
                }

                if (this.count < this.maxCount)
                {
                    this.count++;
                    return true;
                }

                waiter = new AsyncWaitHandle();
                this.Waiters.Enqueue(waiter);
            }

            return waiter.WaitAsync(EnteredAsyncCallback, new EnterAsyncData(this, waiter, callback, state), timeout);
        }
开发者ID:nlh774,项目名称:DotNetReferenceSource,代码行数:25,代码来源:ThreadNeutralSemaphore.cs


示例9: TryAcquire

 public bool TryAcquire(TimeSpan timeout)
 {
     long tm = (long)timeout.TotalMilliseconds;
     if (tm < -1 || tm > (long)Int32.MaxValue)
         throw new ArgumentOutOfRangeException("timeout", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
     return TryAcquire((int)tm);
 }
开发者ID:tijoytom,项目名称:corert,代码行数:7,代码来源:Lock.cs


示例10: NegTest1

    public bool NegTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentOutOfRangeException should be thrown when The parameters specify a TimeSpan value less than MinValue");

        try
        {
            TimeSpan ts = new TimeSpan(Int32.MinValue, Int32.MinValue, Int32.MinValue, Int32.MinValue, Int32.MinValue);

            TestLibrary.TestFramework.LogError("101.1", "ArgumentOutOfRangeException is not thrown when The parameters specify a TimeSpan value less than MinValue");
            retVal = false;
        }
        catch (ArgumentOutOfRangeException)
        {
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("101.0", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
开发者ID:l1183479157,项目名称:coreclr,代码行数:25,代码来源:timespanctor3.cs


示例11: NormalizeTimpstamp0

 public static string NormalizeTimpstamp0(long timpStamp)
 {
     long unixTime = timpStamp * 10000000L;
     TimeSpan toNow = new TimeSpan(unixTime);
     DateTime dt = dtStart.Add(toNow);
     return dt.ToString("yyyy-MM-dd");
 }
开发者ID:corefan,项目名称:uLui,代码行数:7,代码来源:LUtils.cs


示例12: WorkItem

 // Default constructor. If a derived class does not invoke a base-
 // class constructor explicitly, the default constructor is called
 // implicitly.
 public WorkItem()
 {
     ID = 0;
             Title = "Default title";
             Description = "Default description.";
             jobLength = new TimeSpan();
 }
开发者ID:terryjintry,项目名称:OLSource1,代码行数:10,代码来源:inheritance--csharp-programming-guide-_1.cs


示例13: SetTimerCountDownText

        private void SetTimerCountDownText(TimeSpan timeLeft)
        {
            var minutes = timeLeft.Minutes.ToString();
            var seconds = (timeLeft.Seconds < 10) ? "0" + timeLeft.Seconds : timeLeft.Seconds.ToString();

            txtTimerCountDown.Text = minutes + ":" + seconds;
        }
开发者ID:MrOggy85,项目名称:Poker_Blinds_Timer,代码行数:7,代码来源:CounterPage.xaml.cs


示例14: Main

    static void Main(string[] args)
    {
        Console.Title = "Date and time after 6 hours and 30 minutes";

        Thread.CurrentThread.CurrentCulture = new CultureInfo("bg-BG");
        
        Console.ForegroundColor = ConsoleColor.Green;
        Console.Write("Enter a date and time: ");
        string dateAndTime = Console.ReadLine();

        try
        {
            DateTime date = DateTime.ParseExact(dateAndTime, "dd.MM.yyyy HH:mm:ss", CultureInfo.InvariantCulture);

            TimeSpan after = new TimeSpan(6, 30, 0);
            date = date.Add(after);

            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.WriteLine("\nThe date after 6 hours and 30 minutes is: {0} {1:dd.MM.yyyy hh:mm:ss}", date.ToString("dddd"), date);
        }
        catch (FormatException)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("\nYou have entered a wrong date or time!!!");
        }
        finally
        {
            Console.WriteLine();
            Console.ResetColor();
        }
    }
开发者ID:nikolay-radkov,项目名称:Telerik-Academy,代码行数:31,代码来源:DateTImeAfter6HoursAnd30Minutes.cs


示例15: PosTest1

    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Call Duration on a TimeSpan instance whose value is 0");

        try
        {
            TimeSpan expected = new TimeSpan(0);
            TimeSpan actual = expected.Duration();

            if (actual.Ticks != expected.Ticks)
            {
                TestLibrary.TestFramework.LogError("001.1", "Calling Duration on a TimeSpan instance whose value is 0");
                TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual.Ticks = " + actual.Ticks + ", expected.Ticks = " + expected.Ticks);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:27,代码来源:timespanduration.cs


示例16: OpenCollectionAsyncResult

        public OpenCollectionAsyncResult(TimeSpan timeout, AsyncCallback otherCallback, object state, IList<ICommunicationObject> collection)
            : base(otherCallback, state)
        {
            _timeoutHelper = new TimeoutHelper(timeout);
            _completedSynchronously = true;

            _count = collection.Count;
            if (_count == 0)
            {
                Complete(true);
                return;
            }

            for (int index = 0; index < collection.Count; index++)
            {
                // Throw exception if there was a failure calling EndOpen in the callback (skips remaining items)
                if (_exception != null)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(_exception);
                CallbackState callbackState = new CallbackState(this, collection[index]);
                IAsyncResult result = collection[index].BeginOpen(_timeoutHelper.RemainingTime(), s_nestedCallback, callbackState);
                if (result.CompletedSynchronously)
                {
                    collection[index].EndOpen(result);
                    Decrement(true);
                }
            }
        }
开发者ID:SoumikMukherjeeDOTNET,项目名称:wcf,代码行数:27,代码来源:OpenCollectionAsyncResult.cs


示例17: PosTest2

    public bool PosTest2()
    {
        bool retVal = true;
        long randValue = 0;

        TestLibrary.TestFramework.BeginScenario("PosTest2: Call Duration on a TimeSpan instance whose value is a positive value");

        try
        {
            do
            {
                randValue = TestLibrary.Generator.GetInt64(-55);
            } while (randValue == 0);
            if (randValue < 0) randValue *= -1;

            TimeSpan expected = new TimeSpan(randValue);
            TimeSpan actual = expected.Duration();

            if (actual.Ticks != expected.Ticks)
            {
                TestLibrary.TestFramework.LogError("002.1", "Calling Duration on a TimeSpan instance whose value is a positive value");
                TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual.Ticks = " + actual.Ticks + ", expected.Ticks = " + expected.Ticks + ", randValue = " + randValue);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] randValue = " + randValue);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:35,代码来源:timespanduration.cs


示例18: SceneManager

    private SceneManager()
    {
        mUpdateCallback = new EditorApplication.CallbackFunction(EditorUpdate);
        if (EditorApplication.update == null)
        {
            EditorApplication.update += mUpdateCallback;
        }
        else if (!EditorApplication.update.Equals(mUpdateCallback))
        {
            EditorApplication.update += mUpdateCallback;
        }

        mRefreshThreshold = new TimeSpan(0, 0, 0, SECONDS_TO_WAIT, 0);

        // We force a config.xml read operation before the SceneManager is used
        // to avoid inconsistencies on Unity startup.
        mDoDeserialization = true;

        // Make sure that the scene is initialized whenever a new instance of
        // the SceneManager is created.
        mSceneInitialized = false;

        // Unity does not allow to store global editor settings in a comfortable
        // way so we store them in a file.
        ReadProperties();
    }
开发者ID:jhoe123,项目名称:Yonatan-Project,代码行数:26,代码来源:SceneManager.cs


示例19: AcceptWebSocketAsync

 public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync(string subProtocol,
     int receiveBufferSize,
     TimeSpan keepAliveInterval,
     ArraySegment<byte> internalBuffer)
 {
     throw new PlatformNotSupportedException();
 }
开发者ID:dotnet,项目名称:corefx,代码行数:7,代码来源:HttpListenerContext.Unix.cs


示例20: UserLoginSession

        public UserLoginSession(string sessionID, long id, TimeSpan sessionTimeout)
        {
            SessionID = sessionID;
            Id = id;

            SessionTimeout = sessionTimeout;
        }
开发者ID:shrknt35,项目名称:System,代码行数:7,代码来源:UserLoginSession.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# TimeSpanResult类代码示例发布时间:2022-05-24
下一篇:
C# TimeSeries类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap