C# Convert Datetime To Custom Format
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
Solution 1:
Try this
ord.invoiceDate = ((DateTime)dt.Rows[i]["invoicedate"]).ToString("dd-MM-yyyy");
Solution 2:
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");
Post a Comment for "C# Convert Datetime To Custom Format"