Sql convert date format - sql

I want to convert dateformat from mm/dd/yyyy to yyyy/mm/dd. I want the output in datetime format.
I tried this
convert(datetime,convert(varchar,getdate(),111),123)
but doesn't work. The error is "explicit conversion to datetime not available"
What is the best way to solve this problem? I'm using Sybase.

Try this
select convert(varchar,CAST('12/11/2010' as DateTime),111)

That won't work. The DATETIME data type has its own format that is really the amount of time that has passed since a fixed reference date; if you ask for a DATETIME it will always be returned according to that format.
How it is displayed to an end user is a function of the client. You can use CONVERT to convert it to a string and specify a format for how it is displayed in the string, but then you're returning a string, not a DATETIME. You can return it as a DATETIME (which has no inherent display format), and then it is up to the client application or OS to define how it is formatted for display. In client applications you also typically have formatting functions that display a date/time according to a format you specify. And if you haven't specified it explicitly in an application, then the display of the date/time will typically be defined by the localization settings in the OS.
Basically, there is a difference between the data type - DATETIME - and its representation to end users.

Formatting is something that should be done in the presentation tier not the data tier. However, most vendors, like Sybase, provide the ability to do rudimentary formatting:
Select Cast( Year(GetDate()) As char(4) )
+ '/' + Right( '00' + Cast( Month(GetDate()) As varchar(2) ), 2 )
+ '/' + Right( '00' + Cast( Day(GetDate()) As varchar(2) ), 2 )

Try this query
select (CONVERT(varchar(10), GETDATE(), 120))

Related

Change the numeric format into 'AM/PM' format in CONCAT / MAX (sql)

I need to change the numeric format into 'AM/PM' format in CONCAT function (I use SSMS v 18.5.1)
Here is my formula. RCLDTE - is a date and RCLTIM is time. I basically need to leave RCLDTE as it is and change the format of RCLTIM from numeric to date and convert to AM/PM format.
How the column looks right now
Format of RCLTIM - numeric
CONCAT(c.RCLDTE, ' & ', MAX(c.RCLTIM)) AS 'Date & Time',
When I tried to use CONVERT function as I tend to use, it raised an error.
CONCAT(c.RCLDTE, ' & ', CONVERT(varchar(15),CAST( MAX(c.RCLTIM) AS TIME),100))
Error
Explicit conversion from data type numeric to time is not allowed.
The number for the date can be concatenated to the number for the time stuffed with colons. So that it can be converted to a DATETIME.
And by using FORMAT the DATETIME can be put in a specific format.
(But use CONVERT if it has the format.)
Test snippet
declare #test table (
ID INT IDENTITY PRIMARY KEY,
RCLDTE int,
RCLTIM int
);
insert into #test (RCLDTE, RCLTIM) values
(20220119, 215250)
, (20220304, 070809)
;
select
FORMAT(TRY_CAST(CONCAT(c.RCLDTE, ' ', STUFF(STUFF(FORMAT(MAX(c.RCLTIM),'000000'),5,0,':'),3,0,':')) AS DATETIME)
, 'd/M/yyyy hh:mm:ss tt') AS [Date & Time]
from #test c
group by RCLDTE;
Date & Time
19/1/2022 09:52:50 PM
4/3/2022 07:08:09 AM
Test on db<>fiddle here
What you're attempting to do is very fragile, but I presume your source system gives you few options.
Converting like this has potential problems with DST & the language in use at the time of running.
Your question lost some of the detail regarding formats, so I can't see the time type you are using, but it looks like a decimal again.
Essentially, you need to put the the numerics in a string and then into datetime columns, but to get there you have to match a string conversion format the sqlserver.
Fortunately you are not far off the us format default.
Something like this will get you a date field, you can then amend the output format if you really need 12hr rather than 24hr.
SET LANGUAGE us_english
DECLARE #rcldte NUMERIC, #rcltim numeric
SET #rcldte=20220119
SET #rcltim = 015250
SELECT
CONVERT(DATETIME, CAST (#rcldte AS VARCHAR)+ ' ' +
LEFT( left('000000', 6-LEN(CAST ( #rcltim AS VARCHAR)))+CAST ( #rcltim AS VARCHAR),2)
+ ':' + substring( left('000000', 6-LEN(CAST ( #rcltim AS VARCHAR)))+CAST ( #rcltim AS VARCHAR),3,2)
+ ':' + RIGHT( left('000000', 6-LEN(CAST ( #rcltim AS VARCHAR)))+CAST ( #rcltim AS VARCHAR),2))
Which will give you:
(No column name)
2022-01-19 01:52:50.000
It's rather ugly though.
If you can guarantee the hours are zero padded then you could remove the complexity associated with that.
And if you're really going to use it then split into proper UDFs...
DECLARE #RCLDTE CHAR(8) = '20220119';
DECLARE #RCLTIM CHAR(6) = '215250';
select CONVERT(VARCHAR(21), (cast(#RCLDTE as DATETIME) + cast(substring(#RCLTIM,1,2)+':'+substring(#RCLTIM,3,2)+':'+substring(#RCLTIM,5,2) as DATEtime) ), 22);
output: 01/19/22 9:52:60 PM
For different formats of the DATETIME, see the docs of the CONVERT function:
https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver15
NOTE: When specifying another format the value 21 in VARCHAR(21) might need a change...

date time stored as varchar in sql how to filter on varchar

I am working on a project in which dates and times ar stored as a varchar e.g. "30-11-2017,7:30" first date in dd-mm-yyy format and then time separated with a comma. I am trying to filter on it but it is not working correctly kindly guide me how to filter data on date.
select *
from timetrack
where startDateAndTime >= '30-11-2017,7:30'
In attached image records have been shown. When I apply above query it shows no records
You can easily convert your date to SQL datatype datetime uisng parse function, for example select parse('30-11-2017,7:30' as datetime using 'it-IT').
So, in your case, you can apply this function in where clause, so you can easily apply comparison between dates:
select *
from timetrack
where parse(startDateAndTime as datetime using 'it-IT') >= '2017-11-30 07:30:00.000'
Your format is apparently italian :) But you have to specify your own date in the format convertable to datetime, as I have done in above example.
NOTE: parse is available starting with SQL Management Studio 2012.
Unless you are using ISO date format (yyyy-MM-dd HH:mm:ss or close) applying ordering (which inequalities like greater than or equal use) will not work: the date order is disconnected from the string ordering.
You'll need to parse the date and times into a real date time type and then compare to that (details of this depend on which RDBMS you are using).
If, you want to just filter out the date then you could use convert() function for SQL Server
select *
from timetrack
where startDateAndTime >= convert(date, left(#date, 10), 103)
Else convert it to datetime as follow
select *
from timetrack
where startDateAndTime >= convert(datetime, left(#date, 10)+' ' +
reverse(left(reverse(#date), charindex(',', reverse(#date))-1)), 103)
You need the date in a datetime column, Otherwise you can't filter with your current varchar format of your date.
Without changing the existing columns, this can be achieved by making a computed column and making it persisted to optimize performance.
ALTER TABLE test add CstartDateTime
as convert(datetime, substring(startDateAndTime, 7,4)+ substring(startDateAndTime, 4,2)
+ left(startDateAndTime, 2) +' '+ right(startDateAndTime, 5), 112) persisted
Note: this require all rows in the column contains a valid date with the current format
Firstly, you need to check what is the data that is entered in the 'startDateAndTime' column,then you can convert that varchar into date format
If the data in 'startDateAndTime' column has data like '30-11-2017,07:30', you would then have to convert it into date:
SELECT to_date('30-11-2017,07:30','dd-mm-yyyy,hh:mm') from dual; --check this
--Your query:
SELECT to_date(startDateAndTime ,'dd-mm-yyyy,hh:mm') from timetrack;

Convert date format doesn't take effect on self made date string in SQL Server

I have a rather strange issue here. I have a date string, which I've created partly by myself to incorporate a variable. The problem is, that I'm setting another language settings. In this case, I have to also convert the string to fit the language settings format. I'm using this code:
cast(convert(varchar, cast(cast(getdate() as date) as varchar) + ' ' + RIGHT('0' + CAST(#HR as varchar), 2) + ':00:00.000', 120) as datetime)
I get the error "The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.", which is normal if you assign wrong date format before casting.
The problem is, that when I try to convert the personally created date string, it doesn't change its format no matter what format code I set it in. That doesn't change even when I hardcode a number instead of my variable:
convert(varchar, cast(cast(getdate() as date) as varchar) + ' 0' + CAST(2 as varchar) + ':00:00.000', 101)
results in 2016-09-14 02:00:00.000
For example,
convert(varchar, dateadd(Hour, 2, getdate()), 101) as datetime
Results in 09/14/2016.
Even though I have a different language setting, isn't SQL server supposed to always recognize the date format in the standard format?
Please give me an advice so I can overcome this issue.
Thanks in advance!
PS: I managed to solve my issue by inserting converted datetime column in a variable before setting bulgarian language. I'm still very interested to know what causes the problem though.
Ok I may have a soution for the question: Why is the format differently handled in SQL-SERVER when converting.
CONVERT(data_type(length),expression,style)
The STYLEvalue only applies for date/time.
So it's because of the datatype that the output is different.
See following example:
SELECT convert(varchar, dateadd(Hour, 2, getdate()), 101) as datetime
You get the result:
09/14/2016
Here your are converting a datetime datatype into a varchar and the STYLE-value with 101 applies for CONVERT and the output is converted in that format.
Example 2 is the same but the inner most part is casted into a varchar before converting it:
SELECT convert(varchar, CAST(dateadd(Hour, 2, getdate()) AS varchar), 101) as datetime
The result you get is:
Sep 14 2016 4:09PM
So because we are trying to convert a varchar into a varchar the STYLE-value doesn't apply for the conversion.
That is also why the first query is handled diffrent then the other:
SELECT convert(varchar, cast(cast(getdate() as date) as varchar) + ' 0' + CAST(2 as varchar) + ':00:00.000', 101)
Here you cast into varchar cast(cast(getdate() as date) as varchar) before converting. So the STYLE-value is not applying because it's not from datatype date/time.
I hope it made it a bit clear. Let me know if this helped.
When you use convert to format the datetime, you can pass a style number to it.
Looky here or here for those numbers.
The query below converts custom created datetimes to the 126 (ISO8601) format.
declare #d int = 2;
SELECT
CONVERT(varchar,
CONVERT(datetime,
CONCAT(FORMAT(GETDATE(),'yyyy-MM-dd'),' ',#d,':0')
)
,126) AS MyDateStamp1,
CONVERT(varchar,
CONVERT(datetime,
CONVERT(varchar,GETDATE(),102)+' '+convert(varchar,#d)+':0'
)
,126) AS MyDateStamp2;
The FORMAT & CONCAT functions can be used in SQL Server 2012 and beyond.
But if you have an earlier version then CONVERT should work instead.
Additional tip:
If you're using the CONVERT solution above, note that
"convert(varchar, CAST(dateadd(Hour, 2, getdate()) AS varchar), 101)" calls for you to set datatype to varchar.
I just came across code
"Convert(date,ML.StartDate,101)"
and since style 101 is mm/dd/yyyy, and the output was yyyy-mm-dd, I knew something was wrong. By changing the code to
"Convert(varchar,ML.StartDate,101)"
the proper date style was displayed in the result set.

How can convert 15000000.00 to 15,000,000 in SQL server?

There is a one value 15000000.00 with Numeric datatype in SQL server.
How can i get or convert the value 15000000.00 to 15,000,000?
The database server is the wrong place to do this. Localization should be handled in the presentation layer, not the datastore.
Since you're working with the money type, or you want the result to be a money type it could be as simple as:
SELECT CONVERT(VARCHAR, #money_val, 1) -- you may have to cast to money from int first
Check out this link for a deeper discussion:
Here is an excerpt:
Comma-formatting is available only for
MONEY data types. If you want to
comma-format INT, DECIMAL etc, you
should cast it to MONEY and do a
convert with style flag 1.
DECLARE #m DECIMAL(10,2) SELECT #m =
'23456789.25'
SELECT
CONVERT(VARCHAR, #m, 1) AS DecimalValue,
CONVERT(VARCHAR, CAST(#m AS MONEY), 1) AS MoneyValue /*
DecimalValue
MoneyValue
23456789.25 23,456,789.25
*/
This is not a conversion. 15.000.000,00 (german writing) is the string representation of 15 million. A decimal data type does not store the string, but the value.
All string represenration you see are basically visualizations - in enterprise manager or software according to the settings (locale) when generating the string.
I've always used the following with success
SELECT
Convert(VARCHAR, Cast(100000.01 AS MONEY), 1) Amount
Results:
Amount
-----------------------------
100,000.01
You don't want to save your numeric data in formats. You can do this when selecting:
SELECT CONVERT(varchar(12), value, 1) AS formattedvalue FROM table
The last 1 is a convert style that puts in the . and , signs (depending on your local settings and numeric type).
If you ask me, I wouldn't even let the SQL database server worry about this and format the number in code itself.

How can i change datetime format in sql?

How can i change dateformat?Forexample:
2009-06-10 10:16:41.123->2009-June
2009-05-10 10:16:41.123->2009-May
You should not change the date-format in your database.
You should just make sure that , when displaying the date, you correctly format the date, so that you display them in the format that you want.
How to do that, is related to the language you use in your program.
You can also output the date directly in the format you want using the method of ck.
Try this:
select cast(datepart(year, mydatecolumn) as char(4)) + '-'
+ datename(month, mydatecolumn)
from mytable
To interpret input use SET DATEFORMAT
To cast to character, see the CONVERT styles.
To format output, use whatever your client environment uses to format output, SQL itself has no output but TDS and display is left to the client.
Its a pain to do custom formats without writing your own function.
best i have is
SELECT NewFormat = YEAR(GETDATE()) + '-' + DATENAME(month, GETDATE())