可能重复: DateTime.TryParse世纪控制C#
我有一个C#应用程序,它从.DBF文件中导入数据,并将其插入Server中。文件中有一个道布列,其格式是可怕的MM/dd/yy格式。我只使用Convert.ToDateTime,大多数数据都会像我预期的那样转换到1900年。有一些记录不能正确转换,而且30年后人们就出生了。如何强制转换仅写MM/dd/19XX
因此,例如,.DBF文件中的这个日期,12/29/29被转换为12/29/2029。
我读取.DBF文件的方式如下:
var fileInfo = new System.IO.FileInfo(dbfPath);
string dsPath = fileInfo.DirectoryName.ToString();
DataSet DSResult = new DataSet();
using (OleDbConnection cn = new OleDbConnection(
@"Provider=Microsoft.Jet.OLEDB.4.0;" +
@"Data Source=" + dsPath + ";" + //Set the Data Sourde = to the directory of the file.
@"Extended Properties=dBASE III;"))
using (OleDbCommand cm = cn.CreateCommand())
{
cn.Open();
cm.CommandText = "SELECT * FROM UPDATED"; //Specify the file name for the select statement.
using (OleDbDataAdapter dba = new OleDbDataAdapter(cm))
{
dba.Fill(DSResult);
}
}
return DSResult;发布于 2012-03-26 23:14:26
可以更改Calendar.TwoDigitYearMax属性以更改100年范围的最后一年。
DateTimeFormatInfo formatProvider = new DateTimeFormatInfo();
formatProvider.Calendar.TwoDigitYearMax = DateTime.Now.Year;
DateTime date = DateTime.ParseExact("12/12/22", "MM/dd/yy", formatProvider);发布于 2012-03-26 21:55:41
如果您知道检索日期的确切格式,那么可以使用ParseExact()或DateTime ()方法正确地转换日期表示。
它需要一个额外的foramt字符串参数来准确地解析您想要的方式。
dateString = "Sun 15 Jun 2008 8:30 AM -06:00"; // your date string
format = "MM/dd/yy"; // format string
try {
result = DateTime.ParseExact(dateString, format, provider);
}但是,正如注释中提到的那样,数据窗口可能是一个问题。
https://stackoverflow.com/questions/9880309
复制相似问题