我无法将具有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。
出现此错误的原因是,当您使用时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");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句