-1

I am a beginner at C#. I have a DataGridView which displays:

string Column4 = DateTime.Today.AddDays(1).AddHours(7).ToString();

How do I then retrieve just the time value (i.e 07:00:00) as a string later?

EDIT: The date should be in the format it is currently and remain that way in DataGridView, but for example when I do:

 string newString = Column4;
 Console.WriteLine(newString);

How do I just pull the time value from Column4 rather than the whole date?

EDIT2: Saw the possible duplicate question and tried:

 DateTime newString = DateTime.Parse(Column4);
 newString.ToString("HH:mm");
 Console.WriteLine(newString);

But this still produced:

02/05/2018 07:00:00

Logan9Fingers
  • 37
  • 1
  • 3
  • 9

1 Answers1

0

If you only need time value, you can use TimeSpan structure. This structure represents a time interval that you can adjust as you please. You can use the structure constructor and its method ToString() to store the string representation of that time.

This is the code you can use:

string Column4 = (new TimeSpan(7, 0, 0)).ToString();

If you need to use later the same TimeSpan value, I suggest you to store it in a variable:

TimeSpan time = new TimeSpan(7, 0, 0);
string Column4 = time.ToString();

Remember, if you want to make reference of a date, you can use DateTime structure. Else, if you need only the time, you can use TimeSpan structure.

To convert a TimeSpan structure to a Datetime structure you can do this:

DateTime date = DateTime.Today + new TimeSpan(7, 0, 0)).ToString();

Update: If you just need the time from a DateTime structure variable, you can format it:

string newString = DateTime.Parse(Column4).ToString("t");

// Result: 7:00

Or

string newString = DateTime.Parse(Column4).ToString("T");

// Result: 7:00:00

You can see more string formats at this Microsoft MSDN page.

In this Microsoft MSDN page is an example about how to instantiate a TimeSpan structure with desired time:

By calling one of its explicit constructors. The following example initializes a TimeSpan value to a specified number of hours, minutes, and seconds:

TimeSpan interval =  newTimeSpan(2, 14, 18);
Console.WriteLine(interval.ToString()); // Displays "02:14:18". 
CryogenicNeo
  • 937
  • 12
  • 25