C#, how do I make a clock work with added hours?
Question
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);
the part with the timespan does add 2 hours to the clock, however, instead of just the actually clock I also get the date on it's left, like for example:
"17-05-2011 22:38:00"
I need to know how can I add/subtract hours and only show the clock.
Solution
Instead of adding a timespan, simply call the AddHours method:
myDateTime.AddHours(2).ToLongTimeString();
OTHER TIPS
myDateTime.ToShortTimeString() will return you only time
or as Tejs
mentioned you can use ToLongTimeString()
that I guess more suits your requirement.
For adding or subtracting hours you can use dateTime.AddHours(even hours in negative)
or for subtracting you can also use dateTime.Subtract(time to subtract)
Using the .ToString() method of the timespan method allows you to output the date in any format you want. See http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
- For your time zone needs, use an approach similar to the one suggested in this MSDN article. Notably:
- Use
ConvertTimeToUtc
to get UTC time before performing any arithmetics. - Perform required arithmetics.
- Convert back to local time using
TimeZoneInfo.ConvertTime
.
- Use
- To get just the time part of a
DateTime
, useDateTime.ToShortTimeString()
. Note that this is culture-aware, so if you want a fixed format, consider usingDateTime.ToString()
to specify a format.