我无法将具有属性 in0 和 out0 的对象“Time”从字符串转换为 DateTime。
for (int row = 2; row <= rw; row++)
{
for (cCnt = 6; cCnt <= 6; cCnt++)
{
var in0 = (String)(xlworkSheet.Cells[row, 7]
as Excel.Range).Value;
Time.In0 = in0;
Console.WriteLine(Time.In0.ToString());
DateTime dtnew = DateTime.Parse(in0);
Excel.Range formatRange;
formatRange = xlNewSheet.Cells[row, 7];
formatRange.NumberFormat = "hh:mm";
xlNewSheet.Cells[row, 7].Value = Time.In0;
}
}
//this is my class
public class DateandTime
{
public string In0 { get; set; }
public string Out0 { get; set; }
public string In1 { get; set; }
public string Out1 { get; set; }
public string In2 { get; set; }
public string Out2 { get; set; }
public string In3 { get; set; }
public string Out3 { get; set; }
public string In4 { get; set; }
public string Out4 { get; set; }
public string break_time { get; set; }
}
mscorlib.dll 中出现类型为“System.FormatException”的未处理异常
附加信息:字符串未被识别为有效的日期时间。
出现此错误的原因是当您使用 DateTime.Parse(string)
时,线程的当前区域性用于解释该日期/时间。如果您不提供日期,.NET 会假定它是今天,但它不知道时间格式:它不知道如何解释 4 位数字。我们必须提供有关如何解释此字符串的信息。
解决此问题的一种方法是使用 DateTime
的 TryParseExact
方法,然后格式化结果:
private static bool TryFormatTime(string time, out string formattedTime)
{
formattedTime = null;
DateTime parsedDate;
if (!DateTime.TryParseExact(time, "HHmm", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out parsedDate))
{
return false;
}
formattedTime = parsedDate.ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture);
return true;
}
或者您可以将其作为字符串操作来处理。下面的代码验证长度,所有的字符都是数字,然后添加一个 :
:
private static bool TryFormatTime(string time, out string formattedTime)
{
formattedTime = null;
if (time.Length != 4 || !time.All(c => char.IsDigit(c)))
{
return false;
}
formattedTime = string.Format("{0}:{1}", time.Substring(0, 2), time.Substring(2, 2));
return true;
}
这两个都可以按如下方式使用:
if (TryFormatTime("0655", out time))
{
Console.WriteLine(time);
}
else
{
Console.WriteLine("bad time");
}
Try them online
我是一名优秀的程序员,十分优秀!