日期时间类型转换器 [英] DateTime TypeConverter

查看:327
本文介绍了日期时间类型转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的代码到一个字符串类型T.它工作正常的所有其他类型却给人当T DateTime类型的错误进行转换。

 的TypeConverter C = TypeDescriptor.GetConverter(typeof运算(T)); 
回报率(T)c.ConvertTo(OBJ的typeof(T))



我通过像

  OBJ =09/09/2009


它抛出一个错误{'DateTimeConverter'是无法转换'System.String'到'System.DateTime的'。}


解决方案

如果你知道你会得到一个字符串,可以使用 TypeConverter.ConvertFromString 来代替。与 DateTimeConverter 的作品,虽然我不知道为什么的ConvertTo 没有。



例如,这个作品:

 的TypeConverter C = TypeDescriptor.GetConverter(typeof运算(日期时间)) ; 
Console.WriteLine((DATETIME)c.ConvertFromString(09/09/2009));



另外,刚 ConvertFrom 的作品,以及:

 的TypeConverter C = TypeDescriptor.GetConverter(typeof运算(DATETIME)); 
Console.WriteLine((DATETIME)c.ConvertFrom(09/09/2009));



这将转换的的一个日期时间,因为这是种转换器是的。



您应该小心的,虽然文化问题。


I have the below code to convert a string to the type T. It works fine for all other types but gives an error when T is of type DateTime.

TypeConverter c = TypeDescriptor.GetConverter( typeof (T) );
 return (T) c.ConvertTo( obj, typeof (T) )

I pass in a string like

obj =  "09/09/2009"

It throws an error {"'DateTimeConverter' is unable to convert 'System.String' to 'System.DateTime'."}

解决方案

If you know you're getting a string, you can use TypeConverter.ConvertFromString instead. That works with DateTimeConverter, although I don't know why ConvertTo doesn't.

For instance, this works:

TypeConverter c = TypeDescriptor.GetConverter( typeof (DateTime) );
Console.WriteLine((DateTime) c.ConvertFromString("09/09/2009"));

Alternatively, just ConvertFrom works as well:

TypeConverter c = TypeDescriptor.GetConverter( typeof (DateTime) );
Console.WriteLine((DateTime) c.ConvertFrom("09/09/2009"));

It's going to convert to a DateTime because that's the kind of converter it is.

You should be careful of cultural issues though.

这篇关于日期时间类型转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆