简体   繁体   English

将日期时间转换为另一种格式

[英]Convert date time to another format

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:我正在尝试使用以下代码将日期时间从 2019 年 12 月 17 日 19:13:14:850 转换为 17/12/2019 19:13:

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"您的初始字符串的格式实际上是: "dd MMM yyyy hh:mm:ss:fff"

MM gives you the month number, whereas MMM gives you the abbreviated month name. MM为您提供月份编号,而MMM为您提供缩写的月份名称。 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.此外,由于您使用的是 ParseExact,您需要删除日期部分中的: s,因为它们不存在于您的字符串中。

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然后,如果您想将其发送到17/12/2019 19:13 ,格式将为"dd/MM/yyyy hh:mm" -您的也未引用,但我认为这是原文中的错字邮政

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:编辑:正如其他回答者指出的那样,在这两种情况下,您都应该使用HH而不是hh ,因为时间格式是 24 小时,所以:

"dd MMM yyyy HH:mm:ss:fff" and "dd/MM/yyyy HH:mm" "dd MMM yyyy HH:mm:ss:fff""dd/MM/yyyy HH:mm"

The small hh is causing the problem here as you are parsing a 24-hour format.当您解析 24 小时格式时,小hh会导致问题。

The values should be dd MMM yyyy HH:mm:ss:fff and dd/MM/yyyy HH:mm值应为dd MMM yyyy HH:mm:ss:fffdd/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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM