I believe this should be a fairly easy task but somehow it fails. I have dates stored in a text-field like dd-mm-yyyy and I'm converting them to DateTime-types using CONVERT(datetime, [MyDateAsTextField], 105). But the output I''m getting is yyyy-dd-mm 00:00:00.000 and I'm not sure why. What am I missing?
You are getting the output as a date/time in the correct format used for output. Dates and times are stored in an internal format. convert() translates values between strings and the internal format.
If you want the output in a different form, you can use convert(varchar(), . . .) to get the format you want.
More importantly, though, you should not store date/time values strings. You should use the built-in types. They offer much more functionality.
Instead of using datatype as datetime use Char(10) or Varchar(10) and the date style like 105 for dd-mm-yy (Italian).
E.g.:
CONVERT(Char(10), getdate(), 105)
Output will be: 20-02-2015
Related
I'm getting an error I didn't expect to see when using CONVERT with an ISO formatted string, but only when specifying a style code (I've tried a few, and they all throw the error).
For example, this succeeds and returns the datetime in my local format:
select CONVERT(datetime, '2020-01-15T00:00:00')
But this fails with an error
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value
select CONVERT(datetime, '2020-01-15T00:00:00', 103)
I feel I must be missing something very basic here. Can anyone explain?
103 forces the format for convert().
Otherwise, convert() is somewhat flexible on the format you can provide. It does not just use the default format.
Your format, in fact, is the standard format for date/time values. And so it recognizes that regardless of the local settings. Similarly, a string YYYYMMDD is always recognized as a valid date, regardless of the local settings.
I have a scenario to cast string date into date format. But the date string is not in a straight format, so the conversion throws error. So what I tried is
set dateformat dmy
before the casting in sql and it worked without any issue.
But the trouble is I need this to implement in a view or function. But the disappointing part, function or view doesn't support set dateformat with which it says as side effecting operator
So how can I specify the date format of the given string before casting in a function or view?
The third parameter of CONVERT() allows to provide a format type.
Assuming your SET DATEFORMAT DMY I take you've to deal with dates like "1/2/2000", meaning the first of February in 2000.
Try this:
DECLARE #d VARCHAR(100)='1/2/2000';
SELECT CONVERT(DATE,#d,104)
The 104 is the German type with a 4-digit year. If this does not fit your needs, you can follow the link to find a better suiting format.
If you need further help, please provide samples of your actual dates.
Hint: You should always store a value in a column with the appropriate type. Storing dates as strings will make things slow and opens a lot of error sources...
As Damien wrote in his comment to the question, ideally you should not mess around with string representations of datetime in the first place - you should be using proper data types - and since you asked about creating a view, it can only mean that somewhere in your database there's a datetime value stored as a string.
The solution to this situation is to change the way you are storing this value - use DateTime2 for datetime values, Date for date-only values, or Time for time-of-day values.
Further reading - Aaron Bertrand's Bad habits to kick : choosing the wrong data type
Assuming you can't change the database design, read the rest of this answer.
You can't use set dateformat on a view or a function, but you can use convert instead of cast to change the string representation of a datetime value into an actual datetime value, assuming the string representation has one of the supported date formats (there are quite a few of them, so usually it shouldn't be a problem).
If your string representation of the datetime is in a format that is not supported by the built in convert function, you might need to do some extra work in the form of string manipulation to either change it into a supported format, or (in the harder case) separate the string representation to parts and then use datetimefromparts.
If you could provide the actual format you are using in your string representation of the datetime format I can probably edit this answer to show you exactly how to do it.
SELECT CONVERT(varchar(10),CAST('07/01/2018' AS DATE),23)
Result
2018-07-01
Not sure what you mean by, "date string is not in a straight format". Examples will help.
Have you tried parsing, instead of casting?
SELECT
TRY_PARSE(thedate AS datetime) as justParse
,TRY_PARSE(thedate AS datetime USING 'en-US') as parseUS
,TRY_PARSE(thedate AS datetime USING 'en-GB') as parseGB
,try_cast(thedate as date) as tryCast
FROM (values
('07/01/2018')
,('01/07/2018')
,('07 jan 2018')
,('jan 07 2018')
,('Monday, 7 January 2019')
)d(thedate)
Can anyone help me in writing a query for creating a table which will store date in the format of month/date/year (mm/dd/_ _ _ _)?
I do not want to use varchar, because I will be needing to compare my dates also. I also do not want to use any other date formats because my inputs are being entered in the format of month/date/year (mm/dd/_ _ _ _)?
You can use varchar and it can be converted using the option 101 to the format you want (mm/dd/yyyy).
SELECT CONVERT(varchar(10), CONVERT(datetime, '2017/10/02', 111), 101)
The answer is going to depend on what type of database you are using (SQL Server, MySQL, PostgreSql, etc.) and whether you are doing this with 100% SQL, or if you have an application that uses another language that could manipulate the data as well.
Assuming this is an all SQL application, if you need to compare the dates, you will likely need to use the native Date data type for whatever database you are using.
By contrast, you could store it as a varchar, but then would need to cast it as a date for comparison.
To get the date into the format the you are needing, again depending on the database, you may have some sort of date_format function available to input/output the date in the format that you need. If there is not a native function for your database, someone has likely come up with a solution for that database. Searching for your database type (MySQL, Postgresql, etc.) and "date format" will be a good starting point.
If your application is also using another language, it may also have some native functions to convert the date into the format that you need.
I know this didn't directly answer your question, but hopefully gets you thinking about different ways to solve the problem and gets you pointed in the right direction.
You can use varchar and then convert it to your desired format. Here is a sample query.
DECLARE #s DATETIME
SELECT #s = CONVERT(DATETIME, '03/13/2013', 101)
Don't know why but while running the command
select CONVERT(datetime, getdate(),101)
gets '2016-10-27 15:53:12.743', which is the desired result.
However when the same command is run in a Stored Procedure like
if #CodeFilter2 is not null
select #CodeFilter2=CONVERT(datetime,GETDATE(),101)
yields 'Oct 27 2016 3:55PM'.
Please help me understand as to why is this happening.
Thanks in advance!
You're converting a datetime to a datetime? Are you expecting that the format used in convert sticks around? It's just ignored, since it has no meaning for the conversion you're doing. If you want to convert a datetime to a varchar, you need to use something like convert(varchar(max), getDate(), 101), which will give you the correct output 10/27/2016 - I have no idea why you'd expect either of your samples to be correct; they simply happen to work that way because the default conversion (based on locale and other context, which is very variable) happens to be your desired result (in the first case).
If you need to rely on specific formatting you must use explicit formatting. Or let the application handle it instead of the DB server. The proper format for the ODBC cannonical form (which seems to be the one you desire) is 121. Make sure you're converting to varchar or nvarchar, not datetime.
I know that it is possible to reformat the DateTime data type of the current date and time by using select convert. However, I havent been able to find a method to reformat an existing column (DateTime data type) to: hh:mm:ss yyyy/mm/dd. Or even better, I would like to reformat it to show time only. I dont want to simply convert to time data type because I am working with a chart that accepts either Date or Date time. But what I really want to display on that specific axis of the chart is time. Is there any way to reformat DateTime to my requirements? Thanks.
SQL Server's convert function can take an optional style argument depending upon the datatype. This is how you can get a datetime converted to a string in a variety of formats. For example, try running:
select convert(varchar(30), getdate(), 108) -- returns hh:mi:ss
You can replace getdate() in this example with a column name as well.
There are many styles available, as shown in the documentation.
Note that you will be returning a varchar, so you may want to sort by the original column's datatype.
You can use SET DATEFORMAT but this will change all DateTime's on your SQL Server. You can do some custom formatting, but it will convert the DateTime into a VarChar, so you won't be able to treat it as a DateTime.
SET DATEFORMAT: http://msdn.microsoft.com/en-us/library/ms189491.aspx
I'm not sure if you will be able to use the format you're asking about, though.