I need to convert datetime from 2012-07-29 10:53:33.010 to
29/07/2012 10:53:33.
I tried using
select CONVERT(varchar(20), GETDATE(), 131)
but its showing date according to Hijri calendar
11/09/1433 10:53:33:
Please help?
SELECT FORMAT(your_column_name,'dd/MM/yyyy hh:mm:ss') FROM your_table_name
Example-
SELECT FORMAT(GETDATE(),'dd/MM/yyyy hh:mm:ss')
This can be done as follows :
select CONVERT(VARCHAR(10), GETDATE(), 103) + ' ' + convert(VARCHAR(8), GETDATE(), 14)
Hope it helps
You could combine 2 formats:
3 dd/mm/yy (British/French)
8 hh:mm:ss
according to CONVERT() function, and using + operator:
SELECT CONVERT(varchar(10),GETDATE(),3) + ' ' + CONVERT(varchar(10),GETDATE(),8)
SELECT CONVERT(CHAR(10),GETDATE(),103) + ' ' + RIGHT(CONVERT(CHAR(26),GETDATE(),109),14)
The chapter on CAST and CONVERT on MSDN Books Online, you've missed the right answer by one line.... you can use style no. 121 (ODBC canonical (with milliseconds)) to get the result you're looking for:
SELECT CONVERT(VARCHAR(30), GETDATE(), 121)
This gives me the output of:
2012-04-14 21:44:03.793
Update: based on your updated question - of course this won't work - you're converting a string (this: '4/14/2012 2:44:01 PM' is just a string - it's NOT a datetime!) to a string......
You need to first convert the string you have to a DATETIME and THEN convert it back to a string!
Try this:
SELECT CONVERT(VARCHAR(30), CAST('4/14/2012 2:44:01 PM' AS DATETIME), 121)
Now you should get:
2012-04-14 14:44:01.000
All zeroes for the milliseconds, obviously, since your original values didn't include any ....
CREATE FUNCTION DBO.ConvertDateToVarchar
(
#DATE DATETIME
)
RETURNS VARCHAR(24)
BEGIN
RETURN (SELECT CONVERT(VARCHAR(19),#DATE, 121))
END
select DATE_FORMAT(NOW(),'%d/%m/%Y %h:%m:%s')
from dual
Try this wherever required, I have used this in JpaRepository in SpringBoot Project.
This will be varchar but should format as you need.
RIGHT('0' + LTRIM(DAY(d)), 2) + '/'
+ RIGHT('0' + LTRIM(MONTH(d)), 2) + '/'
+ LTRIM(YEAR(d)) + ' '
+ RIGHT('0' + LTRIM(DATEPART(HOUR, d)), 2) + ':'
+ RIGHT('0' + LTRIM(DATEPART(MINUTE, d)), 2) + ':'
+ RIGHT('0' + LTRIM(DATEPART(SECOND, d)), 2)
Where d is your datetime field or variable.
Related
I have a query on SQL Server that's finding wrong results based on a datetime condition.
SET LANGUAGE Português
select distinct
CONVERT(varchar(10), DATENAME(MONTH, i9_parcelaBase.i9_data_vencimento)) + '/' + CONVERT(varchar(10),
DATENAME(YEAR,i9_parcelaBase.i9_data_vencimento)) AS Periodo,
i9_parcelaBase.i9_data_vencimento,
i9_parcelaBase.i9_data_limite_envio_nf,
i9_parcelaBase.i9_status_atual,
i9_processo_statusBase.i9_status,
i9_processo_statusBase.i9_name
--i9_nota_fiscalBase.i9_nota_fiscalid as ID
from i9_parcelaBase
left join i9_processo_statusBase
on i9_parcelaBase.i9_status_atual = i9_processo_statusBase.i9_processo_statusId
where i9_processo_statusBase.i9_entidade = 100000002
and i9_parcelaBase.i9_data_vencimento between CONVERT(varchar(10), year(getdate())-1) + '-' + CONVERT(varchar(10), month(getdate())+1) + '-1'
and CONVERT(varchar(10), year(getdate())) + '-' + CONVERT(varchar(10), month(getdate())) + '-1'
order by i9_data_vencimento asc
Basically, Month that's receiving data without '0' before (when necessary).
Sample:
Actual return: '2017-6-1'
Expected return '2017-06-01'
Can anyone help me to solve this problem?
By the look of your query, i9_data_vencimento is expected to end with just -1, not -01. You can cast the string into a date, then recast it back as a string as a way to format it:
select distinct
CONVERT(varchar(10), DATENAME(MONTH, i9_parcelaBase.i9_data_vencimento)) + '/' + CONVERT(varchar(10),
DATENAME(YEAR,i9_parcelaBase.i9_data_vencimento)) AS Periodo,
CONVERT( VARCHAR(10), CONVERT( DATETIME, i9_parcelaBase.i9_data_vencimento ), 120 ) AS i9_data_vencimento,
:
:
Also, considering that i9_data_vencimento is just a string, and assuming it always ends with '1' in the format 'yyyy-mm-1', you could use a LEFT function to strip off the last character and replace it with '01':
SELECT DISTINCT
:
LEFT(i9_parcelaBase.i9_data_vencimento, 8) + '01' AS i9_data_vencimento,
:
Below is the query which I am trying to run:
SELECT
CONVERT(DATETIME,('12/1/2016' +' '+ '2:00:00')) AS A,
CONVERT(DATETIME,('12/1/2016' +' '+ '2:00:00')) AS B,
DATEDIFF(HOUR, CONVERT(DATETIME, ('12/1/2016' + ' ' + '2:00:00')), CONVERT(DATETIME, ('12/1/2016' + ' ' + '2:00:00'))) as DateDiffernce
Output is:
A B DateDiffernce
2016-12-01 02:00:00.000 2016-12-01 02:00:00.000 0
Let's take 12/1/2016 here the format is DD/MM/YYYY. After using convert function it is getting changed to YYYY-MM-DD which is fine the problem is places are changed i.e 12/1/2016 to 2016-12-01 12 which was the date is shifted or considered as month - which should not happen.
I even tried another query to restrict this conversion which didn't help:
SELECT
CONVERT(DATETIME, CONVERT(CHAR(10), '12/1/2016', 112)
+ ' ' + CONVERT(CHAR(8), '2:00:00', 108))
Kindly help..
Please check #Panagiotis Kanavos comment. He is right. Your query would work fine. Please change the time value like the below to get the DateDifference value.
SELECT CONVERT(DATETIME, ('13/1/2016' + ' ' + '2:00:00'),103) AS A
,CONVERT(DATETIME, ('13/1/2016' + ' ' + '13:00:00'),103) AS B
,DATEDIFF(HOUR, CONVERT(DATETIME, ('13/1/2016' + ' ' + '2:00:00'),103), CONVERT(DATETIME, ('13/1/2016' + ' ' + '13:00:00'),103)) AS DateDiffernce
Hello All Thankyou for your inputs, i was able to solve the issue by
using following code
SET DATEFORMAT YDM
Cheers!! Enjoy coding
I would like to return my datetime data to the following format:
mm/dd/yy hh:mi:ssAM
According to the CONVERT documentation the closest thing that matches my spec is '131'
SELECT CONVERT(varchar, GETDATE(), 131)
but it doesn't exactly match my specifications.
EDIT:
I ended up doing the date formatting in my application layer which is PHP.
It was as simple as using the strtotime function to generate a UNIX timestamp and pass it into date funciton.
$date = date('m/d/Y g:ia', strtotime($row['date_time']));
Try this:
SELECT CONVERT(varchar, GETDATE(), 101) +
REPLACE(CONVERT(varchar, GETDATE(), 0),REPLACE(CONVERT(varchar, GETDATE(),107), ',',''),'')
This basically uses a method that's what you want for the DATE, then adds it to the time portion of what you want for the time only.
Although I feel that formatting should really be part of the UI, I guess if you really need it the below works - I'm sure there is an easier way to do this - but make this a UDF, and just use it in whatever query you want.
declare #date varchar(50)
set #date = (select CONVERT(varchar, GETDATE(), 131))
set #date = (select LEFT(#date,len(#date) - 6) + ' ' + RIGHT(#date,2))
set #date = right(#date,LEN(#date) - 11)
select CONVERT(varchar, GETDATE(), 101) + #date
You can assemble it from DATEPART()'s, and create a user defined function from it for easy re-use.
This is untested off the top of my head.. give it a shot:
CREATE FUNCTION fnSpecDate()
RETURNS VARCHAR(24)
AS
BEGIN
DECLARE #outData VARCHAR(24)
set #outData =
CONVERT(varchar,DATEPART(mm,GETDATE())) + "/"
+ CONVERT(varchar,DATEPART(dd,GETDATE())) + "/"
+ CONVERT(varchar,DATEPART(yy,GETDATE())) + " "
+ CASE WHEN DATEPART(hh,GETDATE()) > 12
THEN CONVERT(varchar,DATEPART(hh,GETDATE()) - 12)
WHEN DATEPART(hh,GETDATE()) = 0
THEN '12'
ELSE CONVERT(varchar,DATEPART(hh,GETDATE()))
END + ":"
+ CONVERT(varchar,DATEPART(mm,GETDATE())) + ":"
+ CONVERT(varchar,DATEPART(ss,GETDATE()))
+ CASE WHEN DATEPART(hh,GETDATE()) > 11
THEN "PM"
ELSE "AM"
END
RETURN #outData
END
Then in any regular query, you can just include dbo.fnSpecDate() as myDate
I will have an integer calculated from datediff()
let's say.. it is..
declare #earliestTime int;
set #earliestTime=50000000;
I want to convert to hh:mm:ss tt
I have this code to convert that int to HH:mm:ss
CONVERT(varchar(6), (#earliestTime)/60)+ ':' + RIGHT('0' + CONVERT(varchar(2), ((#earliestTime) % 60) ), 2)+ ':' + RIGHT('0' + CONVERT(varchar(2), ((#earliestTime) %60)*0), 2)
How can I modify it to hh:mm:ss tt (AM or PM)
I modified like this..
CONVERT(varchar(6),
case
when
((#earliestTime)/60)<=12
then
((#earliestTime)/60)
else
(((#earliestTime)/60)-12)
end )
--CONVERT(varchar(6), case when((#earliestTime)/60)<=12 then (#earliestTime)/60 else ((#earliestTime)/60)-12)
+
':'
+
RIGHT('0' + CONVERT(varchar(2), ((#earliestTime) % 60) ), 2)
+
':'
+
RIGHT('0' + CONVERT(varchar(2), ((#earliestTime) %60)*0), 2
+
' '
+
convert(varchar(2),(case when ((#earliestTime)/60)<12 then 'am' else 'pm' end)))
But it gives me this error..
Conversion failed when converting the
varchar value 'pm' to data type int.
I already convert 'pm' or 'am' to varchar(2). why the system still gives me that error?
How to make it correct or is there a better way?
You don't explain what your integer represents so it is difficult to give an answer.
It's best to use a proper data type for times. I'd use DATETIME - it will allow to you to perform calculations, sort, and format as required. Storing time as text is going to cause headaches later on.
Store a time by adding the time to the SQL epoch (1900-01-01 00:00:00), like so
SELECT DATEADD(SECOND, 50000, CONVERT(DATETIME, 0.0))
SELECT DATEADD(MINUTE, 50000, CONVERT(DATETIME, 0.0))
Then format the DATETIME object accordingly.
To get HH:mm:ss, use format 108.
To get the AM/PM flag, use 100 and take the two rightmost characters.
Try the below:
DECLARE #date DATETIME
SET #date = DATEADD(SECOND, 50000, CONVERT(DATETIME, 0.0))
SELECT CONVERT(VARCHAR, DATEPART(HOUR, #date)%12)
+ ':' + RIGHT(CONVERT(VARCHAR, #date, 108),5)
+ RIGHT(CONVERT(VARCHAR, #date, 100), 2)
I should also point out that you are working in a database, not a presentation layer. There should be no need to worry about formatting dates and times in a database; it is about data storage and retrieval. Presumably you are returning this time to an application or webpage to be put onto a screen, into a report or whatever - best practice is to keep the data as a complete DATETIME and let the top layer format it. By converting to a VARCHAR you are just removing information and limiting yourself; no benefit, lots of cost.
I want to display date time as eg. Dec 1, 09 11:22:45 PM using SQL query
Currently my format is :
DATENAME(Month, (((MachineGroups.TimeAdded*10000000)+ 621355968000000000) -599266080000000000) / 864000000000) + SPACE(1) + DATENAME(d, (((MachineGroups.TimeAdded*10000000)+ 621355968000000000) - 599266080000000000) / 864000000000) +', ' + DATENAME(year, (((MachineGroups.TimeAdded*10000000)+621355968000000000) - 599266080000000000) /864000000000) + SPACE(1)+DATENAME (hour,(((MachineGroups.TimeAdded*10000000)+621355968000000000) - 599266080000000000) / 864000000000) + ':' +DATENAME (minute,(((MachineGroups.TimeAdded*10000000)+ 621355968000000000) - 599266080000000000) / 864000000000) + ':' +DATENAME (second,(((MachineGroups.TimeAdded*10000000)+ 621355968000000000) - 599266080000000000) / 864000000000) AS Expr2
Ussing the above i get eg. December 1, 2009 23:22:45
I tries using the cuatom formata of "MMM" and "yy" but it did not work
any suggestions???
thanks
Is there no way i can use the Datename property above to get my desired format??
It is much easier and more efficient to return the value as a generic datetime object and format it in your UI.
What is your motivation for returning a formatted date from the database?
This will get you everything but AM/PM:
declare #myDate datetime
set #myDate = getdate()
select LEFT(DATENAME(MM, #myDate),3) + ' ' +
RIGHT('0'+DATENAME(DD, #myDate),2) + ', ' +
RIGHT(DATENAME(YY, #myDate),2) + ' ' +
convert(varchar,(DATEPART(hour, #myDate))) + ':' + convert(varchar,(DATEPART(minute, #myDate))) + ':' + convert(varchar,(DATEPART(second, #myDate)))
There are various ways to achieve the AM/PM values, among them would be a substring of:
SELECT convert(varchar, getdate(), 109)
As well as MONTHNAME (which you're already using), check out DATEPART. It's also not far from the CONVERT format of 9 [via CONVERT (VARCHAR(20), #datetime, 9)], so you could manipulate this as well.
Yet another option is using two CONVERTs ... this gives you what you want, but the time's in 24hr format:
SELECT CONVERT(VARCHAR(20), #datetime, 107) + ' ' + CONVERT (VARCHAR(20), #datetime, 108)
Use a different conversion function and a bit of string manipulation to get you 12 hour with AM/PM. Or do something like this:
SELECT CAST(DATEPART(hh, #datetime) - 12 AS VARCHAR)
+ ':' + CAST(DATEPART(mi, #datetime) AS VARCHAR)
+ ':' + CAST(DATEPART(ss, #datetime) AS VARCHAR)
+ CASE WHEN DATEPART(hh, #datetime) BETWEEN 0 AND 11 THEN ' AM' ELSE ' PM' END
Neither this or manipulating the output of CONVERT is pretty, but they're your best options.
HOWEVER: as others have pointed out though, this is normally better done client/UI-side rather than SQL-side.
You can find all supported SQL Server formats here.
To select in a format equivalent to Dec 1, 09 11:22:45 PM, you could use the date from format 7: Mon dd, yy. The time can be assembled from format 109: mon dd yyyy hh:mi:ss:mmmAM (or PM). Combined:
select
convert(varchar(10), getdate(), 7) +
' ' +
stuff(
substring(
convert(varchar(32), getdate(), 109)
,13,14) -- Substring HH:mi:ss.mmmAM
,9,4,' ') -- Replace .mmm by one space
This should print:
Nov 24, 09 4:58:36 PM
The second of the two spaces between 09 and 4 is reserved for a two-number hour, like 11:59:59 PM. :)