简体   繁体   中英

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 ?

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.

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);

Try dataRow[index]. Value .ToString()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM