ASP.NET C#中日期和字符串之间的转换

时间:2011-07-11 10:56:32

标签: c# asp.net string datetime

我现在在使用ODBC连接到Sybase数据库的动态ASP.NET C#Web应用程序中工作,我的主要问题是我的应用程序中datetime和字符串数据类型之间的转换。

数据库以下列形式保存日期时间数据: -

7/11/2011 05:05:05
I think it is in the pattern of "MM/dd/yyyy hh:mm:ss"

我需要调用Web服务并传递一些datetime参数以获得正确的输出。 Web服务接受的静态日期时间格式为: -

11/07/11 09:09:09
I think it is in the pattern of "dd/MM/yy hh:mm:ss"

我尝试单独使用以下功能

string s = d.toString(string format)
DateTime d = Convert.ToDateTime(string s)
DateTime d = s.Datetime.Parse(string format)
DateTime d = s.Datetime.ParseExact(string format)

将我从数据库获得的日期转换为适合传递给Web服务但它总是给我不同的例外,如: -

异常:System.FormatException:String未被识别为有效的DateTime。在WebApplication1.WebForm1.callWebservice()的System.DateTime.Parse(String s)的System.DateTimeParse.Parse(String s,DateTimeFormatInfo dtfi,DateTimeStyles样式)

我不知道如何以正确的方式使用和转换日期,当我尝试许多示例和函数时,我感到很失望,但我无法获得正确的方法逻辑。

我希望找到能帮助的人,并提前致谢.....

3 个答案:

答案 0 :(得分:2)

您应该可以使用DateTime.ParseExact

尝试以下DateTime d = DateTime.ParseExact("11/07/11 09:09:09", "dd/MM/yy hh:mm:ss", null);

答案 1 :(得分:0)

您的Web服务是否需要字符串或实际的日期时间对象?

您是否尝试过yyyy-MM-dd hh:mm:ss格式的日期时间,因为这种格式应该被普遍认可?

答案 2 :(得分:0)

按照链接,有关于DateTime格式的所有内容:

http://www.csharp-examples.net/string-format-datetime/