Reputation: 145
I'm querying a datetime
(dd/mm/YYYY hh:mm:ss) value from a database and inserting it in a list like this:
ord.invoiceDate = dt.Rows[i]["invoicedate"].ToString();
How can I convert this string to a custom format like dd-MM-YYYY
? I don't want the hours minutes and seconds.
Upvotes: 3
Views: 4033
Reputation: 63065
If you know the Format of date time string, then you can use DateTime.ParseExact
method as below to convert it to DateTime. If you not sure about the format then use DateTime.TryParseExact
it will not raise exception on fail to convert but you will get null value as result.
var invoiceDate = DateTime.ParseExact(dt.Rows[i]["invoicedate"],
"dd/mm/YYYY hh:mm:ss", CultureInfo.InvariantCulture);
After you got the result you can convert to string by giving format as below
ord.invoiceDate = invoiceDate.ToString("dd-MM-yyyy");
Upvotes: 2
Reputation: 6692
Try this
ord.invoiceDate = ((DateTime)dt.Rows[i]["invoicedate"]).ToString("dd-MM-yyyy");
Upvotes: 5