Link to home
Start Free TrialLog in
Avatar of dcass
dcassFlag for United States of America

asked on

Simple SQL Date Formula

I have searched for literally five hours and cannot find such a simple thing.
I am creating an SQL database and want to put in a column formula for both a date and a time field (both defined datetime).
I need one to be the date in yyyy/mm/dd format and one to be mm/dd/yyyy hh/mm format.
I've tried putting in the above (I know that minutes are nn) "yyyy/mm/dd" & "mm/dd/yyyy hh/nn"  respectively but it gives the error "Error validating the formula for column 'TDate'".
I feel like this is the most ridiculous qustion I've ever asked.
Avatar of Brian Crowe
Brian Crowe
Flag of United States of America image

The reason you can't find it is because it doesn't exist.  You are confusing format with data.  The database stores the data... you can pull it into a format if you like but the best way to do this is in an application not in the DB.  SQL does not have a date-only or a time-only datatype.  A datetime is stored as 2 4-byte integer values with one representing the number of days since 1/1/1900 and the other representing the number of milliseconds (more or less) since midnight.  If you give a more detailed example of what you are trying to accomplish then I can get more precise.
Avatar of dcass

ASKER

I know SQL doesn't have a date-only or time-only datatype, but you can put it in different formats by setiing the column format, can't you?  It doesn't have to be in mm/dd/yyyy - I know you can change it in the code, I was just looking for an automatic switch from mm/dd/yyyy to yyyy/mm/dd and thought I could use column format.
Avatar of dcass

ASKER

If you can't do it that way, how do you switch the date in C# from mm/dd/yyyy to yyyy/mm/dd?
Should I store the first field that I want just the date in as a varchar?  How do I strip off the time?
It's stored the same no matter how you put it in as long as it is a valid datetime.  If you want to display it in different formats then you can use the Convert function

SELECT Convert(varchar, TDate, 101) --for mm/dd/yyyy
            Convert(varchar, TDate, 111) --for yy/mm/dd

Check out Convert in BOL for different formats
I'm not sure about C# but in VB.Net i would do something like

myDate.tostring("mm/dd/yyyy") if myDate is a datetime or
CDate(myDateString).tostring("mm/dd/yyyy") if i'm dealing with a date in string form.
Avatar of dcass

ASKER

Also, I want to run a 24 hour clock and not use am/pm.  Is it possible to store it that way so it sorts correctly?
ASKER CERTIFIED SOLUTION
Avatar of Brian Crowe
Brian Crowe
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial