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.

Was it helpful?

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

  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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top