john true
john true

Reputation: 273

Convert datetime to specific format from datatable

I want to convert date time value from datatable to only show time value.

I have below code to make this convert process;

DateTime ST = DateTime.ParseExact(dtPivot.Rows[e.DataRow][0].ToString(), "HH:mm:ss",CultureInfo.InvariantCulture);

ulbTime.Text = ST.ToString("HH:mm:ss");

However this throws an error

String was not recognized as a valid DateTime

I searched however couldn't find a solution for me.

How can I solve this ?

Upvotes: 0

Views: 2339

Answers (2)

T McKeown
T McKeown

Reputation: 12847

Your question asks how to show it so use String.Format to show the time portion

DateTime ST = Convert.ToDateTime(dtPivot.Rows[e.DataRow][0]);

var t = string.Format("{0:hh:mm}",ST);

Upvotes: 1

Greg
Greg

Reputation: 11480

You shouldn't need to parse, since the entry being pulled from the database should already be a DateTime field. So in theory, you should be able to pull the data in the following.

var model = IDbConnection.Query(query);
var time = model.First().Date.ToString("hh:mm:ss");

So if you're using a object relational mapper, such as Dapper your model has a DateTime for the object, then you use the string formatter to do the time.

You could also do:

var time = model.First().TimeOfDay();

Built directly into the DateTime is a time of day, works similar to a date short hand method. You could obviously use a DateReader or DataTable accessing the column information index, with a ToString("hh:mm:ss") to return the time specifically. But, you can't do ToString in some instances, because a DBNull.Value or invalid value will cause a reference exception. So you'll need to sanitize and ensure those odd values can't be passed.

I prefer the above, because the mapper should associate the value based on your defined type. So you don't need any extra casting or converting.

Upvotes: 1

Related Questions