简体   繁体   中英

convert string to datetime in specific format

I have date string as:

Fri Oct 25 22:52:21 2013

I want to convert it into datetime format while sending it to database.

I tried query as:

insert into
 DeccoRaw values
 ( 'A04','005629','ARROW STEPLADDER 3TREAD    13013',
 19.89,1,35.8,'NETT',19.89,'5010845130133',
 cast('Fri Oct 25 22:52:21 2013' as DateTime),
 20,'LADDERS','D19206','A','N','13013',29,'','','','','')

I am using c#.net

Its giving me error:

Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.

When I convert it in c# as: DateTime.Parse('Fri Oct 25 22:52:21 2013')

Error:

string was not recognized as valid datetime

I suggest you use the DateTime method. Look at the link below for information on how to convert using DateTime.

How to: Convert a String to a DateTime in C#

Also it is easier to maintain when converting the data before you send it to the database. Unless you specificly want to convert it with SQL. Then I suggest you have a look at the link below:

How to: Convert a String to DateTime in SQL Server

Due to non-standard format, you might need to parse the stirng with ParseExact before inserting it into DB:

string dateString = "Fri Oct 25 22:52:21 2013";
DateTime dateTime = DateTime.ParseExact(dateString, "ddd MMM d HH:mm:ss yyyy", CultureInfo.InvariantCulture);

Substring to remove the first chars as you dont the day of the week name. I'm not sure that it is always 3 chars so you might want to add some kind of test to find the first instance of space.

declare @crap as nvarchar(2000)
set @crap = 'Fri Oct 25 22:52:21 2013'
select CONVERT(datetime , substring(@crap,4,len(@crap)))

You could then use that directly in an insert Something like this maybe

insert into DeccoRaw values
 ( 'A04','005629','ARROW STEPLADDER 3TREAD    13013',
   19.89,1,35.8,'NETT',19.89,'5010845130133',
   CONVERT(datetime , substring('Fri Oct 25 22:52:21 2013' ,4,len('Fri Oct 25 22:52:21   2013' )))       
   20,'LADDERS','D19206','A','N','13013',29,'','','','','')

Crazy way of doing it but you said you wanted strickly sql.

尝试检查数据库中日期的类型,否则检查短日期,长日期...所使用的格式,并以这种格式通过DateTime 转换日期转换字符串

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM