如何将字符串类型的系统日期转换为datetime类型 [英] how to to convert system date of string type to datetime type

查看:108
本文介绍了如何将字符串类型的系统日期转换为datetime类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SqlCommand cmd = new SqlCommand("insert into tblUserRole(UserRoleName,CreatedDate,ModifiedDate) values(@RoleName,@CreateDate,@ModifyDate)", con);
            //SqlCommand cmd = new SqlCommand("insert into tblUserRole(UserRoleName) values(@RoleName)", con);

            string strcreateDate = System.DateTime.Now.ToString();
            DateTime c;
            c = new DateTime();
            c = DateTime.ParseExact(strcreateDate, "yyyy-MM-dd HH:mm tt ", null);


这给了错误


here it is giving error

String was not recognized as a valid DateTime.



我要插入sql server2012.有人可以帮忙.我只需要从系统获取日期并存储在字符串中,将该字符串作为参数传递给wcf服务,并通过webservice



i am inserting in sql server 2012 .can someone help..i just need to take date from system and store in string pass that string as parameter to wcf service and store date in sql server2012 through webservice

推荐答案



应该这样做:
Hi,

this should do:
c = DateTime.Parse(value);



要将日期转换为具有格式的字符串,我将使用



To convert date to string with format, I would use

var formattedDateTime = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm");


如果您使用ParseExact,则需要字符串格式的日期以完全匹配您提供的格式-显然strcreateDate不会这样做.您可以尝试使用DateTime.Parse(或将DateTime.TryParse用于非错误版本,它会通过bool返回值来报告成功),但是您遇到错误的事实意味着您的系统未设置为使用"yyyy- MM-dd HH:mm tt,因为它是当前的文化.

如果您确实使用Parse或TryParse,他们也会期望使用当前的区域性,因此上面的代码段将起作用.

或者,您可以将格式提供给ToString并直接以期望的格式生成一个字符串:
If you use ParseExact, then it expects the string format date to match exactly the format you give it - and clearly strcreateDate does not do that. You could try DateTime.Parse (or DateTime.TryParse for the non-erroring version, it reports success via a bool return value instead), but the fact that you are getting an error implies that your system is not set to use "yyyy-MM-dd HH:mm tt" as it''s current culture.

If you do use Parse or TryParse, they will also expect the current culture, so your code snippet above will work.

Or, you could provide the format to ToString and produce a string in the expected format directly:
string strcreateDate = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm tt");



但是我要做的方法是直接将DateTime值传递给SQL,而不在任何时候将其转换为字符串-SQL理解DateTime对象,并通过参数化查询将其移交给Sql DateTime字段,它将无需任何转换即可工作.



But the way I would do it is to pass the DateTime value through to SQL directly, without converting it to a string at any point - SQL understands DateTime objects and provided you hand it over via a parametrized query to an Sql DateTime field, it will work without any conversion.


您可以尝试使用DateTime.Parse代替DateTime.ParseExact.
You could try using DateTime.Parse instead of DateTime.ParseExact.


这篇关于如何将字符串类型的系统日期转换为datetime类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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