Change default datetime format when converting to string - sql-server

When a datetime is automatically converted to a string it uses this undesired format:
mon dd yyyy hh:miAM
how can I change this default so it is a more typical format like:
yyyy-mm-dd hh:mi:ss.mmm
Also, I don't want to have to explicitly use a cast/convert each time:
Convert(char(23),__date__,121)
I'd like to use CONCAT() without wrapping a convert around the datetimes. I generally keep appending a string variable by dumping in local variables, etc. as my stored procedures process. In the CATCH, I write this string out, but whenever datetime values are concatenated in, it uses the undesired format.
Sample code:
Declare #Now datetime=GETDATE()
,#Temp varchar(100)
SET #Temp=CONCAT('It is now: ',#now)
PRINT #Temp -----------------------It is now: Feb 8 2019 1:45PM
SELECT #Now -----------------------2019-02-08 13:45:05.247
Print #Now ------------------------Feb 8 2019 1:45PM
Print Convert(char(23),#Now,121)---2019-02-08 13:45:05.247
Output:
It is now: Feb 8 2019 1:45PM
-----------------------
2019-02-08 13:45:05.247
(1 row affected)
Feb 8 2019 1:45PM
2019-02-08 13:45:05.247

If you are writing new code, and you are ok with creating objects to support your desired format, then you can do it in a function.
CREATE FUNCTION dbo.fn_NewDate()
RETURNS varchar(23)
AS
BEGIN
RETURN(CONVERT(VARCHAR(23), GETDATE(), 121));
END
GO
Declare #Now varchar(23) = dbo.fn_NewDate()
,#Temp varchar(100);
SET #Temp=CONCAT('It is now: ', #now)
print #Temp;
Result:
It is now: 2019-02-08 12:43:38.980

Related

compare current datetime between 2 date

Here is my code:
declare #fdate varchar(50)
declare #tdate varchar(50)
declare #diff int
declare #CalFromdate datetime
declare #CalTodate datetime
set #diff = 360
set #fdate = '2016-12-19 09:30:00'
set #CalFromdate = DATEADD(mi,#diff,CONVERT(DATETIME, #fdate))
print #CalFromdate
set #CalTodate = DATEADD(mi,#diff,CONVERT(DATETIME, #tdate))
print #CalTodate
gives me Dec 19 2016 3:30PM as fromdate
I don't want this format.
Either '2016-12-19 09:30:00' or '2016-12-19 09:30:00:0000'. I want to compare my current date getdate() with 2 dates. If I use above output format with my gatedate format, will it work or both should be in same format?
You are only seeing the date in the format Dec 19 2016 3:30PM because that is the completely arbitrary formatting that is applied in SSMS when printing a datetime value.
If you change your code to select instead of print you will return your datetime value in the format 2016-12-19 15:30:00.000 but again, this is just an arbitrary formatting used to display a type of data.
Within your query, your datetime value doesn't actually have a format. It is simply a date and time. Use it in your comparison and worry about the formatting in whatever application you are presenting the data in.
As an aside, you also don't need to bother using convert on your #fdate or #tdate parameters, as you have already specified them as datetime values in your declare statements.

How to convert a varchar field type containing date to a proper date format [duplicate]

This question already has answers here:
Convert varchar into datetime in SQL Server
(13 answers)
Closed 6 years ago.
I have a varchar field that contains date values like:
02042015
How do I convert it to DATE format that should return the value something like:
2 Apr 2015
You could use CONVERT with 106 format in following:
declare #date varchar(60) = '02042015'
select convert(varchar(20),cast(right(#date,4) + substring(#date,3,2) + left(#date,2) as datetime), 106)
OUTPUT
02 Apr 2015
I thought there would be some conversion format so you could put:
select(convert(datetime,'010109',<some magic number>))
and get the result, but I can't seem to find one that gives the right date
You can try this as well:
declare #dt varchar(6)
select #dt = '010109'
select convert(datetime,RIGHT(#dt,2) + SUBSTRING(#dt,3,2) + LEFT(#dt,2))
Try this
DECLARE #V_DATE VARCHAR(20) = '02042015'
SELECT CONVERT(varchar(11),
CONVERT(datetime,RIGHT(#V_DATE,4)+LEFT(#V_DATE,2)+SUBSTRING(#V_DATE,3,2))
,106)

How to add an hour to time?

I am working with stored procedure while coding I feel some difficulties to add an hour to a time.I mean I have already a predefined time like 08:00 in my database and now I want to add 4 to this time and I want to get result as 12:00. How can I achieve it?? The way which I tried is below,
ALTER PROCEDURE [dbo].[AttandenceEdit1](
#machid numeric(18,0),
)
AS
declare #time as time(0),#castedtime as time(0),
set #timein1=(select convert(time(0), from ShiftType where machId=#machid )// Value=08:00
print #time
set #addvalue =(DATEADD(HH,#timein1,4))
print #addvalue
I want the result 08:00+4=12:00
now it show error like Argument data type time is invalid for argument 2 of dateadd function
You have the arguments to dateadd in the wrong order. This:
declare #time as time(0)
set #time='08:00'
print #time
declare #addvalue time(0)
set #addvalue =(DATEADD(HOUR, 4, #time))
print #addvalue
Will result in:
08:00:00
12:00:00
There are other issues with your stored proc code though that you need to fix (like undeclared variables, surplus comma, logic).
There seems to be a bunch of issues in the code you've supplied, for example #timein1 and #addvalue are not declared.
So here's a simple example:
DECLARE #time AS TIME = '08:00:00'
SELECT #time AS OriginalTime,
DATEADD(HOUR, 4, #time) TimePlus4Hours
Produces:
OriginalTime | TimePlus4Hours
====================================
08:00:00.0000000 | 12:00:00.0000000
Reference:
DATEADD (Transact-SQL)
Returns a specified date with the specified number interval (signed integer) added to a specified datepart of that date.
DATEADD (datepart , number , date )
Try by Changing the DATEADD() function syntax like this:
set #addvalue =(DATEADD(HH,4,#timein1))

SQl Server Timezone offset Calculation

I am storing all my dates in SQL Server Datetime fields in UTC Date.
There is a requirement where by I have to calculate local Datetime in a procedure from the UTC Date field, and for that i have the Time zone offset of the local datetime.
For ex. my Timezone offset is:'05:30:00'
and UTC Date is: 2013-02-09 08:34:12.037
Desired output: 2013-02-09 14:04:12.037
Now is there a simple way where of doing this without DateAdd and splitting the offset in hours and minutes.
You should be able to use the SWITCHOFFSET function. Here is an example:
declare #dt datetime;
set #dt = '2013-02-09 08:34:12.037';
select SWITCHOFFSET(CONVERT(datetimeoffset, #dt), '+05:30') as 'DATETIMEOFFSET',
CAST(SWITCHOFFSET(CONVERT(datetimeoffset, #dt), '+05:30') as datetime) as 'DATETIME'
-- Outputs:
--
-- 2013-02-09 14:04:12.0370000 +05:30 2013-02-09 14:04:12.037
Use the convert with 112:
declare #d datetime
set #d = getdate()
declare #s nvarchar(20)
set #s = convert(varchar, #d, 112)
print #s
That string will have the year, month, seconds etc.. always on the same position
Extract the desired part with substring:
print substring(#s, 1, 4) -- the year
Now recalculate the entire thing to minutes, by multiplying the hours by 60 and adding the minutes. Now substract your minutes delta from that number. Build a new string with the adjusted date-time, and convert that back to datetime. But... if you need to know the date as well, and you want to do it correct.... there is some coding left.
My advice: do use dateadd it's simple and correct (substract minutes is my advice).

failed when converting date and/or time

I am getting value from store procedure in date is 3/25/13 10:06:38 AM and i want to convert this 03/25/2013 10:18:28 . How can i convert this in sql server . Because when i cast this in date time i am getting error . Below #PODTimeOnly is varchar(255) Here i am casting only time and after this i want to cast and store date in another variable.
SET #PODTimeOnly = cast(#PODTime as time)
ERROR MSG :
Conversion failed when converting date and/or time from character string.
Thanks
Not sure I totally understand the desired output, but if you're forced to hack strings together to generate differently formatted datetime values, this may work.
DECLARE #strDate VARCHAR(50) = '3/25/13 10:06:38 AM',
#dtDate DATETIME,
#DateOnly VARCHAR(255),
#TimeOnly VARCHAR(255),
#output VARCHAR(255)
-- cast to datetime first to verify its a valid date
SET #dtDate = CAST(#strDate AS DATETIME)
-- parse/cast date and time to seperate variables
SET #DateOnly = CONVERT(VARCHAR(255),#dtDate,101)
SET #TimeOnly = CONVERT(VARCHAR(255),#dtDate,108)
-- duct tape them back together in the desired string format
SET #output = #DateOnly + ' ' + #TimeOnly
-- outputs '03/25/2013 10:06:38'
SELECT #output AS 'NewStringDate'

Resources