methuselah
methuselah

Reputation: 13216

Omitting date from label text, only showing time

The following code displays the label as Planning horizon: 20/11/2014 08:00:00 to 20/11/2014 09:00:00, how do I get it to display it as Planning horizon: 08:00:00 to 09:00:00.

DateTime startTime = DateTime.Parse("08:00:00");
DateTime endTime = DateTime.Parse("09:00:00");

label1.Text = "Planning horizon: " + startTime + " to "  + endTime;

Upvotes: 1

Views: 93

Answers (3)

Soner Gönül
Soner Gönül

Reputation: 98810

Just format your DateTime's with .ToString() method like;

label1.Text = "Planning horizon: " + startTime.ToString("HH:mm:ss") + " to "  
               + endTime.ToString("HH:mm:ss");

Long Answer

Since you using string + DateTime concatenation, this process will call string + object overload and uses .ToString() method for the second parameter.

From DateTime.ToString() method;

The value of the current DateTime object is formatted using the general date and time format specifier ('G').

This method uses formatting information derived from the current culture. In particular, it combines the custom format strings returned by the ShortDatePattern and LongTimePattern properties of the DateTimeFormatInfo object returned by the CurrentCulture.DateTimeFormat property

And looks like your CurrentCulture's ShortDatePattern and LongTimePattern is dd/MM/yyyy and HH:mm:ss. That's why you get string result based these concated formats.

Upvotes: 1

MikeH
MikeH

Reputation: 4395

Use .ToLongTimeString() or .ToShortTimeString() on your DateTimes.

  DateTime x = DateTime.Now;
  Console.WriteLine(x.ToLongTimeString());
  Console.WriteLine(x.ToShortTimeString());

Will Generate:

9:30:20 AM
9:30 AM

For your specific output you may want to customize the output string, so instead do this:

startTime.ToString("HH:mm:ss")

Which outputs (note the HH outputs in a 24 hour clock):

09:30:14

See this MSDN page for more info on formatting time strings.

Upvotes: 2

eric_the_animal
eric_the_animal

Reputation: 432

Use the TimeOfDay function. See the link below for formatting options. http://msdn.microsoft.com/en-us/library/system.datetime.timeofday%28v=vs.110%29.aspx

Upvotes: 0

Related Questions