将日期转换为dd-MMM-yy时出错

时间:2016-02-07 20:02:41

标签: c# datetime

运行以下代码行时出现错误:

DateTime dt = DateTime.ParseExact(bolShipdate, "dd/MMM/yyyy", null);

错误是:

  

字符串未被识别为有效的DateTime。

bolShipdate值为02-21-2016。我需要将日期转换为21日至2月16日。 我该如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

DateTime.ParseExact的声明

public static DateTime ParseExact(
    string s,
    string format,
    IFormatProvider provider
)

在这里,您需要传递要解析的格式而不是预期的结果。看起来您的字符串格式为MM-dd-yyyy。 然后,您可以使用.ToString(string format以所需格式获取日期:

string date = "02-21-2016";
DateTime dt = DateTime.ParseExact(date, "MM-dd-yyyy", CultureInfo.InvariantCulture);
string newFormat = dt.ToString("dd-MMM-yy");
Console.WriteLine(newFormat);

答案 1 :(得分:2)

ParseExact中的格式需要与您的字符串匹配。 dd/MMM/yyyy与提供的示例数据不匹配。尝试:

    var bolShipdate = "02-21-2016";
    DateTime dt = DateTime.ParseExact(bolShipdate, "MM-dd-yyyy", null);
    Console.WriteLine(dt.ToString("dd-MMM-yy")); // Dispays 21-Feb-16

Example fiddle

答案 2 :(得分:0)

希望这可以解决:

var date = "02-21-2016";
DateTime dt = DateTime.ParseExact(date, "MM-dd-yyyy", CultureInfo.InvariantCulture);
string result = dt.ToString("dd-MMM-yy");