Reputation: 5738
My string contains the value: 08/20/2012-10.32.19
I want the output in string datatype itself as 08/20/2012 10:32:19
[format is MM/dd/yyyy HH:mm:ss
].
Please help!!
Upvotes: 0
Views: 172
Reputation: 53
We have various inbuilt format like ToLongDateTime
, ToShortdateTime
in .Net
string formatDate = txtdte.ToShortDateTime();
This returns string so no need of any other conversion. If you are specific about your format, ToString takes parameters like ToString("dd/mm/yyyy")
Upvotes: 0
Reputation: 223267
You may convert the string to DateTime
and then use .ToString()
with the required format.
DateTime dt = DateTime.ParseExact("08/20/2012-10.32.19", "M/d/yyyy-HH.mm.ss",CultureInfo.InvariantCulture);
string test = dt.ToString("MM/dd/yyyy HH:mm:ss");
Test will have
08/20/2012 10:32:19
EDIT: based on the comment
You may specify multiple date formats and then parse accordingly.
string[] formats = new string[] { "M/d/yyyy-HH.mm.ss", "yyyy-M-d-HH.mm.ss" };
string dtTest1 = DateTime.ParseExact("08/20/2012-10.32.19",
formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None)
.ToString("MM/dd/yyyy HH:mm:ss");
Or in a single line
string dtTest2 = DateTime.ParseExact("08/20/2012-10.32.19",
new string[] { "M/d/yyyy-HH.mm.ss", "yyyy-M-d-HH.mm.ss" },
CultureInfo.InvariantCulture,
DateTimeStyles.None)
.ToString("MM/dd/yyyy HH:mm:ss");
This will satisfy your both case of dates:
08/20/2012-10.32.19
2012-08-20-10.32.19
Upvotes: 8
Reputation: 77
You may use very simple becouse your string only require fiormating
String a="08/20/2012-10.32.19".Replace('-', ' ').Replace('.', ':');
I hope this work for you
Upvotes: 1