Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 247
  • Last Modified:

Convert to datetime

How do I convert this string to datetime?
'25.3.2012 19:41:07'

DECLARE @TimeDay datetime
SET @TimeDay='25.3.2012 19:41:07'
0
johnkainn
Asked:
johnkainn
1 Solution
 
chinawalCommented:
DECLARE @TimeDay datetime
SET @TimeDay= replace('25.3.2012 19:41:07','.','/')

Assuming that your server is  dd/mm/yyyy format
0
 
johnkainnAuthor Commented:
When I run this I get following error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

 When I select GETDATE() I get 2012-03-25 21:30:54.107

When I use following it works
DECLARE @TimeDay datetime
SET @TimeDay='2012-03-25 20:01:54.937'
0
 
chinawalCommented:
oK. try this. this should work.


DECLARE @TimeDay datetime
SET @TimeDay= convert(datetime, '25.3.2012 19:41:07', 104)
select @TimeDay
0
 
waltersnowslinarnoldCommented:
Hi, use the following query sample, this would help you;


DECLARE @v DATETIME
SELECT @v = CONVERT(DATETIME,'25.3.2012 19:41:07',105)
SELECT @v
0
 
Scott PletcherSenior DBACommented:
One of the only 100% safe date formats is YYYYMMDD, so it's safest -- although the code is longer -- to convert to 'YYYYMMDD HH:MM:SS.sss', which works under ALL SQL date and language settings.


DECLARE @TimeString varchar(30)
DECLARE @TimeDay datetime

SET @TimeString = '25.3.2012 19:41:07'

SET @TimeDay = PARSENAME(LEFT(@TimeString, CHARINDEX(' ', @TimeString) - 1), 1) +
RIGHT('0' + PARSENAME(LEFT(@TimeString, CHARINDEX(' ', @TimeString) - 1), 2), 2) +
RIGHT('0' + PARSENAME(LEFT(@TimeString, CHARINDEX(' ', @TimeString) - 1), 3), 2) +
SUBSTRING(@TimeString, CHARINDEX(' ', @TimeString), 30)

SELECT @TimeDay
0

Featured Post

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now