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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Formatting Date and Time

Status
Not open for further replies.
Dec 11, 2009
60
US
I have a date field that I need to be formatted in 2 ways:

1 - I need the field to come out as YYYYMMDD, but what I have is leaving out the '0' in the month field as:

Convert(VarChar(4), year(getdate()))+''+CONVERT(VarChar(2),Month(getdate()))+''+Convert(VarChar(2), Day(getdate())) as createdate: 2010219

2- I need the field to come out as HHMMSSNN? How can I accomplish this?

Thanks for any assistance!
 
Code:
REPLACE(CONVERT(VARCHAR(10), GETDATE(), 102), '.', '')
REPLACE(CONVERT(VARCHAR(11), GETDATE(), 114), ':', '')

djj
The Lord is My Shepard (Psalm 23) - I need someone to lead me!
 
One quick question? How can you change the order of the date if you want it to display as:

REPLACE(CONVERT(VARCHAR(10), GETDATE(), 102), '.', ''

YYYYDDMM?
 
These are very helpful!

Now if I can figure out how to rearrange the order of the date as such: YYYYDDMM that would be awesome?
 
Using 112 should do that for you.

djj
The Lord is My Shepard (Psalm 23) - I need someone to lead me!
 
you picked a strange format :p

There are several ways to achieve your end goal concatenating the date parts and adding leading zeros etc.

I would suggest if it is something that you will use in several places that you create it as a function.

Here is one way:

Code:
DECLARE @dt datetime 
set @dt = GETDATE()-10

SELECT CAST(YEAR(@dt) AS CHAR(4))+REPLACE(LEFT(CONVERT(CHAR(10),@dt,103),5),'/','')

function:

Code:
CREATE FUNCTION [dbo].[YYYYDDMM]  
(@dt DATETIME)
RETURNS VARCHAR(8) AS  
BEGIN 
RETURN CAST(YEAR(@dt) AS CHAR(4))+REPLACE(LEFT(CONVERT(CHAR(10),@dt,103),5),'/','')
END

GO

SELECT [dbo].[YYYYDDMM] ( GETDATE() )

 
Year day month is a problem, as day month year or month day year are available but year month day is all I see for date formats starting with year. (This being easy to sort).

Writing a function might be your best bet.

djj
The Lord is My Shepard (Psalm 23) - I need someone to lead me!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top