I am trying to convert a datetime of like 17 Dec 2019 19:13:14:850 to 17/12/2019 19:13 using the below code:
string dateTime = "17 Dec 2019 19:13:14:850";
DateTime dt = DateTime.ParseExact(dateTime,"dd:MM:yyyy hh:mm:ss:fff",CultureInfo.InvariantCulture);
string s = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
But getting error msg as:
String was not recognized as valid date time.
The format of your initial string is actually: "dd MMM yyyy hh:mm:ss:fff"
MM
gives you the month number, whereas MMM
gives you the abbreviated month name. Also, since you're using ParseExact, you needed to get rid of the :
s in the date portion, because they are not present in your string.
Then, if you're wanting to get it to 17/12/2019 19:13
the format will be "dd/MM/yyyy hh:mm"
- yours is also not quoted, but I will assume that's a typo in the original post
Edit : as the other answerer pointed out, you should be using HH
instead of hh
in both of these cases, as the time format is 24 hours, so:
"dd MMM yyyy HH:mm:ss:fff"
and "dd/MM/yyyy HH:mm"
The small hh
is causing the problem here as you are parsing a 24-hour format.
The values should be dd MMM yyyy HH:mm:ss:fff
and dd/MM/yyyy HH:mm
Try the following
string dateTime = "17 Dec 2019 19:13:14:850";
DateTime dt = DateTime.ParseExact(dateTime, "dd MMM yyyy HH:mm:ss:fff", CultureInfo.InvariantCulture);
string s = dt.ToString("dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.