Wednesday, March 28, 2012

How to format a date field

Hi,
comming from php/mysql some things here on this side are great - but some seems to be solved in a way I can not figure out.
What I need is a way to get a string in the format "yyyy-mm" out of a date-time field like:

09/05/2006 23:12:36 ??should produce ???2006-09 ???as one string

What I figured out by my own is:

SELECT { fn CONCAT({ fn CONCAT(DATENAME(yyyy, dateField), '-') }, STR(DATEPART(mm, dateField))) }, ...

but this returns "2006- ???9" with blanks in it. Or I could use 2 times the DATENAME but this would give 2006-September.
Would it help to use a stored procedure?
Thanks,
Klaus

in SQL, you could do the conversion like this:

declare @.das datetime set @.d =getdate()printconvert(varchar(7),@.d, 20)--convert to yyyy-mm-dd hh:mi:ss but only keep the left 7 chars

my preference is to return dates from sql intact, and then format them at the presentation layer - like this

Protected Sub Page_Load(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles Me.LoadDim dAs DateTime =Date.Now Response.Write(d.ToString("yyyy-MM"))End Sub
sql

No comments:

Post a Comment