datetime format in sql server 2008 - sql-server

I have used below code to convert a datetime to string,
DECLARE #StartDate datetime = '08/07/2015 12:10 AM'
set #StartDate = dateadd(hour,12, #StartDate);
select CONVERT(VARCHAR(10),#StartDate, 101) + RIGHT(STUFF(CONVERT(VARCHAR(32), #StartDate,100), 18, 0, ' '),8)
but I am getting output as "08/07/201512:10 PM" , there is no space between date and time, How can I correct this?

If i correctly understood your problem then there is small correction required in your code. I added +' '+ i.e. a blank space between your date convert and right stuff. Complete code is as given below.
DECLARE #StartDate DATETIME = '08/07/2015 12:10 AM'
SET #StartDate = DATEADD(HOUR,12, #StartDate);
SELECT CONVERT(VARCHAR(10),#StartDate, 101) +' '+
RIGHT(STUFF(CONVERT(VARCHAR(32),#StartDate,100), 18, 0, ' '),8)
Result
08/07/2015 12:10 PM
i.e. space between date and time also space between 12:10 and PM
To cover new case provided :
DECLARE #StartDate DATETIME = '08/07/2015 2:10 AM'
SET #StartDate = DATEADD(HOUR,12, #StartDate);
SELECT CONVERT(VARCHAR(10),#StartDate, 101) +' '+
LTRIM(RIGHT(STUFF(CONVERT(VARCHAR(32),#StartDate,100), 18, 0, ' '),8))
Result
08/07/2015 2:10 PM
i.e. no extra space when time is like 2:10 PM

Here is one way to do it:
DECLARE #StartDate datetime = '2015-08-07T00:10:00';
SET #StartDate = dateadd(hour,12, #StartDate);
SELECT #StartDate As StartDate,
CONVERT(CHAR(10), #StartDate, 101) + ' ' + -- DateString,
SUBSTRING(CONVERT(CHAR(19), #StartDate, 100), 13, 5) + ' ' + -- TimeString
RIGHT(CONVERT(CHAR(19), #StartDate, 100), 2) As DateString -- AM/PM
Result:
StartDate DateString
----------------------- -------------------
2015-08-07 12:10:00.000 08/07/2015 12:10 PM

The following snippet will produce the output you've indicated in the question.
SET DATEFORMAT MDY;
DECLARE #StartDate DATETIME = '08-07-2015 12:10 AM';
SET #StartDate = DATEADD(HOUR, 12, #StartDate);
SELECT CONVERT(VARCHAR, #StartDate, 103) + ' ' +
CONVERT(VARCHAR, CAST(#StartDate AS TIME), 108) +
CASE WHEN DATEPART(HOUR, #StartDate) < 12 THEN ' AM' ELSE ' PM' END;
N.B. As others have pointed out, you would be better off using ISO format for input dates.
Updated dateformat from DMY to MDY and explicitly adding AM/PM to the end.

Related

Print a sentence saying the day of the year using SQL Server

I am trying to write this using SQL SERVER:
"Hi! Today is ... This is the day number... of the year. New year's eve is in ... days".
My code runs with no problem but I can't print as well. What am I doing wrong? I haven't finished the whole phrase because I need to fix the problem before I get to the last part.
DECLARE
#currentDate DateTime
SET #currentDate = GETDATE();
DECLARE #dayofyear datetime
SET #dayofyear=DATEDIFF(day,STR(YEAR(#dayofyear),4)+'0101',#dayofyear)+1
-- SELECT Numbertoday = DATEDIFF(day,STR(YEAR(#dayofyear),4)+'0101',#dayofyear)+1
print('Hi! Today is '+ CONVERT(VARCHAR(10), #currentDate , 111) + '. ' + 'This is the day number '+ ' ' + CONVERT (VARCHAR(10), #dayofyear) + of the year.')
Another way to do is:
declare #today varchar(11) = convert(varchar(11), getdate(), 1);
declare #dayOfTheYear int = datepart(DAYOFYEAR, getdate());
declare #untilNewYearsEve int = datepart(dayofyear, datefromparts(year(getdate()), 12, 31)) - #dayOfTheYear
-- if you use print, you should see the result under the 'messages' tab not in the 'results' tab in SSMS
print 'Hi! Today is '+ #today + '. ' + 'This is the day number '+ cast( #dayOfTheYear as varchar(3)) + '. New year''s eve is in '+
cast (#untilNewYearsEve as varchar(3)) + ' days.'
This should work perfectly fine.
while seeting the day of year you need to put #current date so it will work because you are trying to get a day from a #currentdate
DECLARE
#currentDate DateTime
SET #currentDate = GETDATE();
DECLARE #dayofyear datetime
SET #dayofyear=DATEDIFF(day,STR(YEAR(#currentDate),4)+'0101',#currentDate)+1
print('Hi! Today is '+ CONVERT(VARCHAR(10), #currentDate , 111) + '. ' + 'This is the day number '+ ' ' + CONVERT (VARCHAR(10), #dayofyear) + 'of the year.')
Just for fun, you can use concat()
Example
Print concat('Hi! Today is '
,format(GetDate(),'dddd, MMM d, yyyy.')
,' This is the day number '
,DateDiff(DAY,datename(YEAR,getdate())+'0101',getdate()) + 1
,' of the year.'
)
Results
Hi! Today is Thursday, Jul 4, 2019. This is the day number 185 of the year.
You can simplify things a bit using DAYOFYEAR parameter in the DATEPART function if using SQL 2008 and above. And you don't really need to declare a variable for the date.
Sample Code:
print('Hi! Today is '+ convert(varchar(10), getdate() , 111) + '. ' + 'This is the day number' + ' ' + convert(varchar, datepart(dayofyear, getdate()))) + ' of the year.'
Results:
Hi! Today is 2019/07/05. This is the day number 186 of the year.

TSQL Parameter for specific timeframes (day previous 4PM to today noon)?

I am looking to create a TSQL Parameter for specific timeframes such as MorningTimeFrame will pull yesterday from 4PM until noon today and AfternoonTimeFrame to pull noon today until 4Pm Today. How would I set that up? I'm familiar with the Dateadd(day,datediff(day,1,GETDATE()),0) but not sure how I would set it to a specific time.
You can get these required timeframe values as per below query
Select Cast(Cast(CAST(dateadd(d,-1,getdate()) AS date) as varchar) + ' 16:00:00' as datetime)AS 'MorningStartTime', Cast(Cast(CAST(getdate() AS date) as varchar) + ' 12:00:00' as datetime)AS 'MorningEndAfterNoonStartTime', Cast(Cast(CAST(getdate() AS date) as varchar) + ' 16:00:00' as datetime)AS 'AfterNoonEndTime'
Use this as per convenience
Will something simple suffice?
declare #Start as DateTime, #End as DateTime;
declare #Timeframe as VarChar(32) = 'MorningTimeframe';
-- Start from midnight today.
declare #Today as DateTime = Cast( GetDate() as Date );
-- Calculate the timeframe.
if #Timeframe = 'MorningTimeframe'
begin -- Yesterday 4PM through noon today.
select #Start = DateAdd( hour, -8, #Today ),
#End = DateAdd( hour, 12, #Today );
end
else if #Timeframe = 'AfternoonTimeframe'
begin -- Noon today through 4PM.
select #Start = DateAdd( hour, 12, #Today ),
#End = DateAdd( hour, 16, #Today );
end
else
begin
RaIsError( 'Unexpected timeframe: ''%s''', 16, 42, #Timeframe );
end;
-- Display the results.
select #Today as [Today], #Timeframe as Timeframe, #Start as [Start], #End as [End];

Convert nvarchar to datetime sql server

I try to convert 2016/07/15 (nvarchar format) to this datetime format 2016-07-15 00:00:00 in sql server. But i need the time part to be the current time. can any one help ?
This is my sp:
declare #DateTime varchar(50)
set #DateTime = '2016/07/15'
select convert(varchar, cast(#DateTime as datetime), 120)
You can use this:
declare #DateTime varchar(50)
set #DateTime = CONCAT('2016/07/15' , ' ', CONVERT(TIME, GETDATE()))
select #DateTime
select convert(varchar, cast(#DateTime as datetime2(7)), 120)
Or replace the CONCAT with:
set #DateTime = '2016/07/15' + ' ' + CONVERT(NVARCHAR(50), CONVERT(TIME, GETDATE()))
Try this...
Just concat time with your output
declare #DateTime varchar(50)
set #DateTime = '2016/07/15'
select convert(varchar, cast(#DateTime as datetime), 101) + ' ' + CONVERT(varchar, getdate(),108)
Try like this,
DECLARE #DateTime VARCHAR(50)
SET #DateTime = '2016/07/15'
SELECT DATEADD(day, 0, DATEDIFF(day, 0, #DateTime)) + DATEADD(day, 0 - DATEDIFF(day, 0, getdate()), getdate())

Converting DateTime to nvarchar, just month and year

How to convert the datetime value to nvarchar and want to format it "Month, Year" e-g October 1st 2009 value should get converted to "October, 2009"
use this:
select CONVERT(nvarchar(50), DATENAME(m, getdate())
+ ', '
+ DATENAME(yyyy, getdate())
)
OUTPUT:
--------------------------------------------------
October, 2009
(1 row(s) affected)
Try this
DECLARE #DateTime DATETIME
SET #DateTime = '01 Oct 2009'
SELECT #DateTime
SELECT DATENAME(mm, #DateTime) + ', ' + CAST(DATEPART(yy, #DateTime) AS VARCHAR(4))
One way would be to use datename to extract the pieces you needed in name format, so:
select Convert(nvarchar,datename(m,getdate())) + N', ' + Convert(nvarchar,datename
(yy,getdate()))
And replace getdate() with your date variable / field.
The DateName function will provide the formatting you require:
DATENAME(m, date) + ', ' + DATENAME(yyyy, date)
Converting to nvarchar of a specific size can be done through the cast function:
CAST(value AS nvarchar[30])
Try the following query:
Select case Convert(int, day(getdate())) when 1 then '1st' when 2 then '2nd'
when 3 then '3rd' else Convert(varchar, day(getdate()))+'th' end +' '+ Convert(varchar, Datename(m,getdate()))+' ' +Convert(varchar, Datename(yy,getdate())) as Date
You can replace getdate() with any other date.
Please check if it helps.

Get only the Date part of DateTime in mssql [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Get just the Date from grouping in select from DateTime column in SQL Server
How can I get only the Date part of a DateTime ? I'm searching for something like year() function but for the whole date.
This may also help:
SELECT convert(varchar, getdate(), 100) -- mon dd yyyy hh:mmAM (or PM)
-- Oct 2 2008 11:01AM
SELECT convert(varchar, getdate(), 101) -- mm/dd/yyyy - 10/02/2008
SELECT convert(varchar, getdate(), 102) -- yyyy.mm.dd – 2008.10.02
SELECT convert(varchar, getdate(), 103) -- dd/mm/yyyy
SELECT convert(varchar, getdate(), 104) -- dd.mm.yyyy
SELECT convert(varchar, getdate(), 105) -- dd-mm-yyyy
SELECT convert(varchar, getdate(), 106) -- dd mon yyyy
SELECT convert(varchar, getdate(), 107) -- mon dd, yyyy
SELECT convert(varchar, getdate(), 108) -- hh:mm:ss
SELECT convert(varchar, getdate(), 109) -- mon dd yyyy hh:mm:ss:mmmAM (or PM)
-- Oct 2 2008 11:02:44:013AM
SELECT convert(varchar, getdate(), 110) -- mm-dd-yyyy
SELECT convert(varchar, getdate(), 111) -- yyyy/mm/dd
SELECT convert(varchar, getdate(), 112) -- yyyymmdd
SELECT convert(varchar, getdate(), 113) -- dd mon yyyy hh:mm:ss:mmm
-- 02 Oct 2008 11:02:07:577
SELECT convert(varchar, getdate(), 114) -- hh:mm:ss:mmm(24h)
SELECT convert(varchar, getdate(), 120) -- yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar, getdate(), 121) -- yyyy-mm-dd hh:mm:ss.mmm
SELECT convert(varchar, getdate(), 126) -- yyyy-mm-ddThh:mm:ss.mmm
-- 2008-10-02T10:52:47.513
-- SQL create different date styles with t-sql string functions
SELECT replace(convert(varchar, getdate(), 111), '/', ' ') -- yyyy mm dd
SELECT convert(varchar(7), getdate(), 126) -- yyyy-mm
SELECT right(convert(varchar, getdate(), 106), 8) -- mon yyyy
The Source
The solution you want is the one proposed here:
https://stackoverflow.com/a/542802/50776
Basically, you do this:
cast(floor(cast(#dateVariable as float)) as datetime)
There is a function definition in the link which will allow you to consolidate the functionality and call it anywhere (instead of having to remember it) if you wish.
Another nifty way is:
DATEADD(dd, 0, DATEDIFF(dd, 0, [YourDate]))
Which gets the number of days from DAY 0 to YourDate and the adds it to DAY 0 to set the baseline again. This method (or "derivatives" hereof) can be used for a bunch of other date manipulation.
Edit - other date calculations:
First Day of Month:
DATEADD(mm, DATEDIFF(mm, 0, getdate()), 0)
First Day of the Year:
DATEADD(yy, DATEDIFF(yy, 0, getdate()), 0)
First Day of the Quarter:
DATEADD(qq, DATEDIFF(qq, 0, getdate()), 0)
Last Day of Prior Month:
DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, getdate()), 0))
Last Day of Current Month:
DATEADD(ms, -3, DATEADD(mm, DATEDIFF(m, 0, getdate()) + 1, 0))
Last Day of Current Year:
DATEADD(ms, -3, DATEADD(yy, DATEDIFF(yy, 0, getdate()) + 1, 0))
First Monday of the Month:
DATEADD(wk, DATEDIFF(wk, 0, DATEADD(dd, 6 - DATEPART(day, getdate()), getdate())), 0)
Edit:
True, Joe, it does not add it to DAY 0, it adds 0 (days) to the number of days which basically just converts it back to a datetime.
We can use this method:
CONVERT(VARCHAR(10), GETDATE(), 120)
Last parameter changes the format to only to get time or date in specific formats.
This may not be as slick as a one-liner, but I use it to perform date manipulation mainly for reports:
DECLARE #Date datetime
SET #Date = GETDATE()
-- Set all time components to zero
SET #Date = DATEADD(ms, -DATEPART(ms, #Date), #Date) -- milliseconds = 0
SET #Date = DATEADD(ss, -DATEPART(ss, #Date), #Date) -- seconds = 0
SET #Date = DATEADD(mi, -DATEPART(mi, #Date), #Date) -- minutes = 0
SET #Date = DATEADD(hh, -DATEPART(hh, #Date), #Date) -- hours = 0
-- Extra manipulation for month and year
SET #Date = DATEADD(dd, -DATEPART(dd, #Date) + 1, #Date) -- day = 1
SET #Date = DATEADD(mm, -DATEPART(mm, #Date) + 1, #Date) -- month = 1
I use this to get hourly, daily, monthly, and yearly dates used for reporting and performance indicators, etc.

Resources