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
Related
How would I take the month, append "/01/" to it, then append the year to it, and finally append "00:01 AM" to it. I would like it end up looking like this:
2018/01/01 00:01 AM
I managed to do it in ACCESS but cannot accomplish this in SQL Server. Your help is greatly appreciated!
Using Concat,Cast,Year,Month and right
replace getdate() with your variable/field
select cast(concat(year(getdate()),right(concat('0',month(getdate())),2),'01',' 00:01 AM') as datetime)
or
select convert(varchar(22),cast(concat(year(getdate()),right(concat('0',month(getdate())),2),'01',' 00:01 AM') as datetime),100)
You can get the desired result with this script:
DECLARE #Date DATETIME;
SET #Date = '2018-01-02 13:45:30.000';
SELECT CAST(YEAR(#Date) AS CHAR(4)) + '/' + CASE WHEN MONTH(#Date) >= 10 THEN '' ELSE '0' END + CAST(MONTH(#Date) AS VARCHAR(2)) + '/01 00:01 AM';
Edit:
You can also create a function and make it reusable:
CREATE FUNCTION dbo.InitializeDate(#Date DATETIME)
RETURNS VARCHAR(19)
AS
BEGIN
RETURN CAST(YEAR(#Date) AS CHAR(4)) + '/' + CASE WHEN MONTH(#Date) > 10 THEN '' ELSE '0' END + CAST(MONTH(#Date) AS VARCHAR(2)) + '/01 00:01 AM';
END
GO
-- Usage example:
SELECT dbo.InitializeDate('2018-01-02 13:45:30.000') AS MyDate;
GO
-- Output:
2018/01/01 00:01 AM
There are different ways obviously - and always mention the version you are using since that affects the functionality that is available. I will say that it is highly unusual to require a time portion as you describe. I fear you have made an assumption and chosen a path that may turn into a problem. I suggest you read Tibor's discussion of the datetime datatype (and everything else as well). One possible way - which is really to demonstrate the functionality available in steps to get you thinking - is:
set nocount on;
declare #x datetime = '20180102 13:45:30.000';
with cte as (select cast('20180102 13:45:30.000' as datetime) as d1 union all
select '20180101 13:45:01:997' union all
select '20180228 00:00:05.003' union all
select '20120229 12:11:30.007')
select d1,
datefromparts(year(d1), month(d1), 1),
dateadd(second, 1, cast(datefromparts(year(d1), month(d1), 1) as datetime))
from cte;
I am making a SQL procedure to get me a selection of workers from the table,
where each worker has startJob and endJob date.
What I need is to make selection of all the workers who were on the job
during specified #year and #month. (#year & #month are input params)
I would really appreciate an advice how to solve this the easiest way.
Thx for any help.
If i proper understood you then try something like:
CREATE PROCEDURE [usp_Procedure]
#Year int
, #Month int
AS
BEGIN
select * from workers
where #Year between YEAR(startJob) and YEAR(endJob)
and #Month between MONTH(startJob) and MONTH(endJob)
END
You can make a date from the year and month parameters and compare to the start and end job fields.
This will return the first day of the month/year entered, and return results where this date is between the StartJob and EndJob
select *
from worker
where
CAST(
CAST(#Year AS VARCHAR(4)) +
RIGHT('0' + CAST(#month AS VARCHAR(2)), 2) +
RIGHT('0' + CAST(01 AS VARCHAR(2)), 2)
AS DATETIME)
between
StartJob and EndJob
Create a DATE based on the start of the month for the given year
DECLARE #Year INT = 1999
DECLARE #Month INT = 1
DECLARE #Date DATE = CONVERT(DATE, CONVERT(CHAR, #Month) + '-' + CONVERT(CHAR, #Month) + '-01')
-- SQL Server should now correctly handle the logic to filter out the relevant rows
SELECT *
FROM worker w
WHERE #Date BETWEEN w.startJob AND w.endJob
If you'd rather use the last day of the month, then you could use EOMONTH(#Month) for your DAY.
FINAL SOLVED SELECT ROWS BETWEEN TWO DATE USING ONLY MONTH AND YEAR
begin
declare #trvl_start_date as date
declare #trvl_stop_date as date
declare #trim_start as varchar(20)
declare #trim_end as varchar(20)
declare #trvl_start_date_new as date
declare #trvl_stop_date_new as date
set #trvl_start_date ='2015-10-12'
set #trvl_stop_date='2016-01-01'
set #trim_start = LEFT(#trvl_start_date, CHARINDEX('-', #trvl_start_date) + 2) + '-01'
set #trim_end = LEFT(#trvl_stop_date, CHARINDEX('-', #trvl_stop_date) + 2) + '-01'
print #trim_start
print #trim_end
set #trvl_start_date_new = #trim_start
set #trvl_stop_date_new =dateadd(month,-1,#trim_end)
print #trvl_start_date_new
print #trvl_stop_date_new
SELECT fee_catg_srno FROM dbo.fee_catg_tbl
WHERE (acd_yr = 1) AND (recycle = 1) AND (acc_head_srno = 3) AND pay_date between #trvl_start_date_new and #trvl_stop_date_new
end
With SQL-server 2008 database I have a char(14) data type that I want to convert to a datetime.
Example char(14) values:
20120209102026
20010131120000
The date format is yyyymmdd of some sort.
It seems like the values I posted are not the only format, because I get an "index out of range" error for some of the values. For this I can skip the ones that are not valid dates.
declare #c char(14)
select #c='20120209102026'
Select Cast(Substring(#c,1,8) + ' ' + Substring(#c,9,2)+':'+
Substring(#c,11,2)+':'+ Substring(#c,13,2) as DateTime)
Second Version that ignores out of range numeric values:
Select Cast(
Rtrim(Substring(#c,1,8)
+ Case When len(Substring(#c,9,4))>=4 then +' '+ Substring(#c,9,2) else '' end
+ Case When len(Substring(#c,11,2))=2 then +':'+ Substring(#c,11,2) else '' end
+ Case When len(Substring(#c,13,2))=2 then +':'+ Substring(#c,13,2) else '' end)
as Datetime)
This is ugly but if your format is yyyymmddhhmmss then you can use:
select cast(left(yourDate, 8)+' '+
SUBSTRING(yourDate, 9, 2)+':'+SUBSTRING(yourDate, 11, 2)+':'+RIGHT(yourDate, 2) as datetime)
from yourtable
See SQL Fiddle with Demo
A series of function calls but ends up with the same outcome.
Try like this:
select convert(datetime,STUFF(STUFF(STUFF(STUFF(STUFF('20010131120000',5,0,'/'),8,0,'/'),11,0,' '),14,0,':'),17,0,':'))
Look here for how STUFF works!
Every year I have to update my company's financial reports to include the new financial year (as the year isn't coterminus with the calendar year), so I do.....
Case
when ST_date >= '1996.11.01 00:00:00' and st_date < '1997.11.01 00:00:00'
then '96-97'
[etc]
end as year,
Every year I have to remember which reports I need to amend - most years I forget one!
...Is there a simple dynamic way to determine this?
You could definitely write a simple stored function in SQL Server to determine the financial year based on the date:
CREATE FUNCTION dbo.GetFinancialYear (#input DATETIME)
RETURNS VARCHAR(20)
AS BEGIN
DECLARE #FinYear VARCHAR(20)
SET #FinYear =
CASE
WHEN #INPUT >= '19961101' AND #input < '19971101' THEN '96-97'
WHEN #INPUT >= '19971101' AND #input < '19981101' THEN '97-98'
ELSE '(other)'
END
RETURN #FinYear
END
and then just use that in all your queries.
SELECT
somedate, dbo.GetFinancialYear(somedate)
......
If you need to add a new financial year - just update the one function, and you're done !
Update: if you want to make this totally dynamic, and you can rely on the fact that the financial year always starts on Nov 1 - then use this approach instead:
CREATE FUNCTION dbo.GetFinancialYear (#input DATETIME)
RETURNS VARCHAR(20)
AS BEGIN
DECLARE #FinYear VARCHAR(20)
DECLARE #YearOfDate INT
IF (MONTH(#input) >= 11)
SET #YearOfDate = YEAR(#input)
ELSE
SET #YearOfDate = YEAR(#input) - 1
SET #FinYear = RIGHT(CAST(#YearOfDate AS CHAR(4)), 2) + '-' + RIGHT(CAST((#YearOfDate + 1) AS CHAR(4)), 2)
RETURN #FinYear
END
This will return:
05/06 for a date such as 2005-11-25
04/05 for a date such as 2005-07-25
Have a look at this example:
declare #ST_Date datetime = '20120506'
SELECT
convert(char(2),DateAdd(m,-10,#ST_DATE),2)+'-'+
convert(char(2),DateAdd(m,+ 2,#ST_DATE),2) as year
As a column expression:
convert(char(2),DateAdd(m,-10,ST_DATE),2)+'-'+
convert(char(2),DateAdd(m,+ 2,ST_DATE),2) as year
Pretty trivial!
The way I handle these problems (financial year, pay period etc) is to recognize the fact that financial years are the same as any year, except they start X months later. The straightforward solution is therefore to shift the FY by the number of months back to the calendar year, from which to do any "annual" comparisons or derivation of "year" (or "month").
Declare #FinancialMonth Varchar(100)=NULL,#Month smallint,#Date DateTime='04/06/2013'
BEGIN TRY
SELECT #FinancialMonth='01-'+IsNULL(#FinancialMonth,'April')+'-'+Cast(year(getdate()) as varchar)
SELECT #Month=(Month(Cast(#FinancialMonth as datetime))-1) * -1
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber,'Invalid Financial Month' ErrorMessage
END CATCH
SELECT Month((CONVERT([varchar](10),dateadd(month,(#Month),#Date),(101)))) FinancialMonth,
Year((CONVERT([varchar](10),dateadd(month,(#Month),#Date),(101)))) FinancialYear
,DatePart(qq,(CONVERT([varchar](10),dateadd(month,(#Month),#Date),(101)))) FinancialQuarter
This one works for me and sets it as the actual FY end date.
SET #enddatefy = convert(DATE, str(datepart(yyyy,DateAdd(m,-6,#enddate))+1)+'0630',112)
SET #enddatefyid = str(datepart(yyyy,DateAdd(m,-6,#enddate))+1)+'0630'
datename(YEAR, DATEADD(M,-3,Date)) +'-'+ cast((datepart(YEAR, DATEADD(M,-3,Date)) + 1) %100 as varchar(2))
Calculate on Column 'Date'
Financial year ranges from 1st April to 31st March
Create FUNCTION dbo.GetFinancialYear (#input DATETIME)
RETURNS VARCHAR(20)
AS BEGIN
DECLARE #FinYear VARCHAR(20)
IF (MONTH(#input) > 3)
SET #FinYear = RIGHT(CAST(Year(#input) AS CHAR(4)), 4) + '-' + RIGHT(CAST((Year(#input) + 1) AS CHAR(4)), 2)
ELSE
SET #FinYear = RIGHT(CAST((Year(#input) - 1) AS CHAR(4)), 4) + '-' + RIGHT(CAST(Year(#input) AS CHAR(4)), 2)
RETURN #FinYear
END
Declare #date1 datetime = '2017-07-01'
Select Case
When Month(#date1)>=7 Then 'FY'+Convert(NVARCHAR(10),(Right(year(getdate()),2)+1))
Else 'FY'+Convert(NVARCHAR(10),(Right(year(getdate()),2)))
End
This works for me, where the financial year starts in July.
CASE WHEN DatePart(mm, [YourDate]) >= 7
THEN convert(varchar(10), YEAR([YourDate])) +' / '+ Convert(varchar(10), YEAR([YourDate]) + 1 )
ELSE Convert(varchar(10), YEAR([YourDate]) - 1) +' / '+ Convert(varchar(10), YEAR([YourDate]) )
END AS [Financial Year],
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.