Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Date Conversion 2

Status
Not open for further replies.

meldrape

Programmer
May 12, 2001
516
US
Hello there,

I have a text file with dates in yymmdd format, which I have managed to convert to mm/dd/yy with this:

select CAST ( ENDDATE AS datetime) as ENDDATE from JobImportHeader

but I really need yyyy. Is there a way to convert yy to yyyy? Thanks in advance!

 
I've never done this, but is says it can by done with CONVERT function in SQL BOL. Here's some of what it says:

Using CONVERT:

CONVERT ( data_type [ ( length ) ] , expression [ , style ] )

expression

Is any valid Microsoft® SQL Server™ expression. For more information, see Expressions.

data_type

Is the target system-supplied data type, including bigint and sql_variant. User-defined data types cannot be used. For more information about available data types, see Data Types.

length

Is an optional parameter of nchar, nvarchar, char, varchar, binary, or varbinary data types.

style

Is the style of date format used to convert datetime or smalldatetime data to character data (nchar, nvarchar, char, varchar, nchar, or nvarchar data types), or the string format when converting float, real, money, or smallmoney data to character data (nchar, nvarchar, char, varchar, nchar, or nvarchar data types).

In the table, the two columns on the left represent the style values for datetime or smalldatetime conversion to character data. Add 100 to a style value to get a four-place year that includes the century (yyyy).
(table is in SQL BOL)

 
Thanks, Organicglenn. I did try that in the beginning, but it did not work. CAST worked much better. I can live with the two digit year. Thanks for your input!
 
CAST and CONVERT do exactly the same thing, they are different wording for the same command.

Your CAST ( ENDDATE AS datetime) is the same as doing CONVERT(datetime, ENDDATE).

What you want to look at is the [style] option mentioned by organicglenn. See here
or just use CONVERT(datetime, ENDDATE, 101)...

The other thing to remember is, if you have them in a database column of type datetime - then you can display them in whatever format you like - just use convert and the styles (eg CONVERT(varchar, myDatetimeColumn, 101) )

Posting code? Wrap it with code tags: [ignore]
Code:
[/ignore][code]CodeHere
[ignore][/code][/ignore].
 
I changed the data type in the column from varchar to datetime, and used your second suggestion and it worked. I was afraid it would screw something up, but it worked famously. Many thanks again to both of you for your help.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top