English 中文(简体)
C#,我如何用额外时间24小时工作?
原标题:C#, how do I make a clock work with added hours?

Using Visual Studio 2008 (C#) I have to make a working clock (digital) with the current time zone hour, and a few more with different time zones, like new york, etc.

inside the form I put 2 labels (for the clocks) and a timer, inside the timer I put this code:

 timer1.Interval = 1000;

        label1.Text = DateTime.Now.ToLongTimeString();
        DateTime myDateTime = DateTime.Now;


        TimeSpan myTimeSpan = new TimeSpan(2, 0, 0);
        DateTime myDateTime8 = myDateTime + myTimeSpan;
        label2.Text = ("" + myDateTime8);

但随着时间的推移,24小时又增加了2小时,而实际上,我也离开了这个日期,例如:

“17-05-2011 22:38:00”

我需要知道我如何能够增加/推迟时间,只显示钟。

最佳回答

不要增加一个时间,而是简单地称“AddHours”方法:

myDateTime.AddHours(2).ToLongTimeString();
问题回答

我的假日。

或作为<代码>Tejs提到你可使用<代码>ToLongtimeString(,我认为这更符合你的要求。

增减小时请使用<代码>日。 添加物(即使是负数小时),或用于替代物的,也可使用<代码>datetime.Subtract(时间改为分机)。

采用时间范围方法“ToString”方法,使你能够以你想要的任何形式完成日期。 See

  1. For your time zone needs, use an approach similar to the one suggested in this MSDN article. Notably:
    1. Use ConvertTimeToUtc to get UTC time before performing any arithmetics.
    2. Perform required arithmetics.
    3. Convert back to local time using TimeZoneInfo.ConvertTime.
  2. To get just the time part of a DateTime, use DateTime.ToShortTimeString(). Note that this is culture-aware, so if you want a fixed format, consider using DateTime.ToString() to specify a format.




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签