Convert a string to datetime format in asp .net
Solution 1
First, you should be parsing the string to a DateTime
and then format it to the second format using ToString()
method.
//Convert your string to a DateTime
DateTime dt2 = DateTime.ParseExact(date31strin,
"MM-dd-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
//If you want to change the format
string secondFormat = dt2.ToString("Second format string");
Note: Date is a Date and it does not have a format. If you need to convert the string to a DateTime, first line of code is enough
Solution 2
You are not changing the format. You are parsing a string into a DateTime object which does not have a format.
When you decide to present the DateTime, you can format it any way you wish.
Basim Sherif
Updated on July 09, 2022Comments
-
Basim Sherif almost 2 years
I have a date time string
"12-24-2013 15:19:29"
which is in"MM-dd-yyyy HH:mm:ss"
. I want to convert this string to datetime. But the format should not change.ie, it should be the same"MM-dd-yyyy HH:mm:ss"
format.When I used following method,
DateTime dt2 = DateTime.ParseExact(date31strin, "MM-dd-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
the format is changed to
"dd-MM-yyyy HH:mm:ss"
. I have tried some other method also, but still getting this same format.