[英]getting custom dateTime format from DateTime.TryParse
I read cell values from excel file that has a several data type (string , dateTime , int) . 我从具有多种数据类型(string,dateTime,int)的excel文件中读取单元格值。
And In DateTime cell , that may be in various format likes 12/28/2013
, 8:30
. 并且在DateTime单元格中,可能有各种格式,例如12/ 12/28/2013
: 8:30
。
Using this code , ( cell.ToString()
is excel cell value ) 使用此代码,( cell.ToString()
是excel单元格值)
DateTime _dt;
if (DateTime.TryParse(cell.ToString(), out _dt))
{
//
}
When I read 12/28/2013
, it return 12/28/2013 12:00:00 AM
. 当我阅读12/28/2013
,它12/28/2013 12:00:00 AM
返回。
But when I read 8:30
, it return 12/31/1899 12:00:00 AM
. 但是当我在8:30
读到它时,它将在12/31/1899 12:00:00 AM
返回。
As you can see , I can't get the original time 8:30
. 正如你所看到的,我无法在8:30
获得原始时间。
Am I wrong something ? 我错了什么? OR is there any approach to fix it ? 或者有任何方法来解决它?
You can use TryParseExact
and specify your formats. 您可以使用TryParseExact
并指定格式。 There is an overload taking string[]
patterns array as a parameter: 将string[]
patterns数组作为参数进行重载:
DateTime.TryParseExact
Method ( String
, String[]
, IFormatProvider
, DateTimeStyles
, DateTime
) DateTime.TryParseExact
方法( String
, String[]
, IFormatProvider
, DateTimeStyles
, DateTime
)
You can call it like that: 你可以这样称呼它:
DateTime.TryParseExact(cell.ToString(), new [] { "M/d/yyyy", "hh:mm" }, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out _dt);
You may need Custom Date and Time Format Strings to prepare more patterns to make sure it works for all your input formats. 您可能需要自定义日期和时间格式字符串来准备更多模式,以确保它适用于所有输入格式。
Try like this 试试这样吧
string strDate = "8:00";
string format = "hh:mm";
DateTime res;
bool success = DateTime.TryParseExact(strDate, format, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.