Reputation: 11
I have tried out as many suggestions as I've found on Stackoverflow, but not getting the desired result. Any help would be much appreciated.
My date string is "04-Dec-2013 14:14:02.143" and I want to convert this exactly as into DateTime
format.
This was the last suggestion I tried:
String MyString;
MyString = "04-Dec-2013 14:14:02.143";
DateTime MyDateTime;
MyDateTime = new DateTime();
MyDateTime = DateTime.ParseExact(MyString, "dd-MMM-yyyy HH:mm:ss.fff",
null);
However, I keep getting the undesired result of "04/12/2013 14:14:02" rather want it to be "04-Dec-2013 14:14:02.143".
Any suggestions?
Upvotes: 1
Views: 294
Reputation: 26302
@MarcinJuraszek has better answer on this question, but it does not solve the problem of different datetime patterns, because of what great SO users mark other questions as duplicate.
string MyString = "Dec-12-2013 14:14:02.143";
CultureInfo ukCulture = new CultureInfo("en-GB");
ukCulture.DateTimeFormat.ShortDatePattern = "MMM-dd-yyyy HH:mm:ss.fff";
DateTime myDateTime = DateTime.Parse(MyString, ukCulture.DateTimeFormat);
string QbDate = myDateTime.ToString("dd-MMM-yyyy HH:mm:ss.fff");
To solve the issue of different date-time patterns override any date pattern of any culture
Upvotes: 1
Reputation: 6775
As mentioned by @MarcinJuraszek the format comes into picture when you convert it back to string. The format you mentioned in ParseExact is for the parsing. i.e. How will MyString be parsed to create a DateTime object.
See below example just so you understand how the ParseExact format string is used.
If you use MyDateTime.ToString("dd-MMM-yyyy HH:ss:mm.fff"); instead (see I swapped mm and ss) in ParseExact you will get "12/4/2013 2:02:14 PM" instead of "12/4/2013 2:14:02 PM"
Upvotes: 0
Reputation: 125610
Yes, you should read about DateTime
struct. It has not have any format info attached, it's just a plain number representing point in time.
The format come into play when you try to get string
representation of the data, using ToString(format)
method.
Use the format string every time you're calling ToString
to get the date in the format you want it to be:
var stringDateRespresentation = dateValue.ToString("dd-MMM-yyyy HH:mm:ss.fff");
To make things easier you should pass plain, non-formatted DateTime
instances all around and change it into string
using ToString
method only when it's being presented to the user.
Upvotes: 5