SQL Server getdate() format - sql-server

How to get format like 19 Dec 2012 from getdate() function in tsql
select convert(varchar(11),getdate(),?)

select convert(varchar(11),getdate(),106)

Cast and Convert lists the available formats:
106 dd mon yy
looks about right.
I'd generally avoid doing any formatting on the database. Keep dates as dates as long as possible - only convert at the last moment in displaying it to the user (similarly, for any input, prefer to convert it from string into its proper data type as early as possible)

-- Can use if SQL 2008 and above (precision to nanoseconds)
SELECT CONVERT(VARCHAR(12), SYSDATETIME(), 106)
-- otherwise (precision to miliseconds)
SELECT CONVERT(VARCHAR(12), GETDATE(), 106)

Related

Date format in SQL Server 2012

I have the date in this format 2017-02-03 and I want that my date should be in this format 01-Mar-2016 while making select command.
I am using SQL Server 2012
Check this website. This will be helpful.
select replace(convert(varchar, getdate(), 106),' ','-')
What is done here is: First convert it into '01 Mar 2016' and then replace white spaces(' ') with '-'. Which will give desired output as '01-Mar-2016'
Use SQL Server Format function where you can specify .NET format string
For instance for current date
SELECT FORMAT(GETDATE(), 'dd-MMM-yyyy');
Also you can specify culture here if needed
SELECT FORMAT(GETDATE(), 'dd-MMM-yyyy', 'en-US');
If you dates are stored as string you'd better fix this but you can just CAST or CONVERT them instead. I.e.
SELECT FORMAT(CAST('2017-10-11' AS date), 'dd-MMM-yyyy');

How to convert mm/dd/yyyy militarytime -> mm/dd/yyyy hh:mm:ss AM/PM

I'm using the following code and almost getting what I'm looking for:
SELECT sdb.NAME AS DatabaseName
,COALESCE(CONVERT(VARCHAR(10), cast(max(bus.backup_finish_date) as date), 101) + ' ' + convert(varchar(12), max(bus.backup_finish_date), 108), 'Never Restored') as [LastBackupTime]
FROM sys.sysdatabases sdb
INNER JOIN dbo.backupset bus
ON bus.database_name = sdb.NAME
GROUP BY sdb.NAME,
bus.backup_finish_date
Your result should be something like:
mm/dd/yyyy HH:mm:ss
I'm trying to get
mm/dd/yyyy hh:mm:ss AM/PM
I've tried multiple converts, a series of casts, ltrim/right, and even offering homage to the T-SQL overlords. No luck yet.
I've even tried
SELECT sdb.NAME AS DatabaseName
--Code below needs changed to show Date & time--
,COALESCE(CONVERT(VARCHAR(30), MAX(bus.backup_finish_date), 100), 'Never
backed up.') AS LastBackUpTime
FROM sys.sysdatabases sdb
INNER JOIN dbo.backupset bus
ON bus.database_name = sdb.NAME
GROUP BY sdb.NAME,
bus.backup_finish_date
but that gets me (for example) Mar 21 2017 10:47AM. We really prefer 3/21/2017 10:47AM.
Suggestions? I'm still picking this apart but could use some help.
Thanks!
If you are using SQL Server 2012 or later, you can use FORMAT():
Select Format(Max(bus.backup_finish_date), N'MM/dd/yyyy hh:mm:ss tt')
If you are using SQL Server 2012 or later you can use FORMAT, although be wary of doing this on large data sets.
SELECT FORMAT(GETDATE(), 'MM/dd/yyyy hh:mm:sstt')
For earlier versions, or if performance is a concern, For earlier versions, or if performance is a concern, you can concatenate the date in the format MM/dd/yyyy (style 101), with the time in the format hh:mm:ss (style 8) and a case expression to determine AM or PM
SELECT CONVERT(VARCHAR(10), GETDATE(), 101) + ' '
+ CONVERT(VARCHAR(10), GETDATE(), 8)
+ CASE WHEN DATEPART(HOUR, GETDATE()) < 12 THEN 'AM' ELSE 'PM' END
HOWEVER, formatting is a job for the presentation layer. If it was me doing this, then I would just send the native datetime, including nulls back to the presentation layer and let this handle it. It means that in your application layer you can still work with the dates, perform date calculations, or sort etc without the worry that 15/01/2017 is going to appear after 02/02/2017. It also means you can display dates in the end user's preferred locale, rather than yours.
One easiest way is to use format but it is not highly performant:
select FORMAT(Max(bus.backup_finish_date),'MM/dd/yyyy hh:mm:ss tt')
For earlier versions one another naive way of doing is as below:
Select CONVERT(VARCHAR(10), getdate(), 101) + ' ' + LTRIM(RIGHT(CONVERT(CHAR(20), getdate(), 22), 11))
Instead of GetDate() use your date
But that is already mentioned by #GarethD So never mind

How to convert a datetime to string in T-SQL

I'm surprised not to be able to find this question here already.
I have a date time var and I want to convert it to a string so that I can append it to another string. I want it in a format that can be converted easily back to a date time.
How can I do this?
(I want the date part and the time part.)
The following query will get the current datetime and convert into string. with the following format yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar(25), getdate(), 120)
SQLFiddle Demo
SQL Server Date Formats
There are many different ways to convert a datetime to a string. Here is one way:
SELECT convert(varchar(25), getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm
See Demo
Here is a website that has a list of all of the conversions:
How to Format datetime & date in SQL Server
In addition to the CAST and CONVERT functions in the previous answers, if you are using SQL Server 2012 and above you use the FORMAT function to convert a DATETIME based type to a string.
To convert back, use the opposite PARSE or TRYPARSE functions.
The formatting styles are based on .NET (similar to the string formatting options of the ToString() method) and has the advantage of being culture aware. eg.
DECLARE #DateTime DATETIME2 = SYSDATETIME();
DECLARE #StringResult1 NVARCHAR(100) = FORMAT(#DateTime, 'g') --without culture
DECLARE #StringResult2 NVARCHAR(100) = FORMAT(#DateTime, 'g', 'en-gb')
SELECT #DateTime
SELECT #StringResult1, #StringResult2
SELECT PARSE(#StringResult1 AS DATETIME2)
SELECT PARSE(#StringResult2 AS DATETIME2 USING 'en-gb')
Results:
2015-06-17 06:20:09.1320951
6/17/2015 6:20 AM
17/06/2015 06:20
2015-06-17 06:20:00.0000000
2015-06-17 06:20:00.0000000
SELECT CONVERT(varchar, #datetime, 103) --for UK Date format 'DD/MM/YYYY'
101 - US - MM/DD/YYYY
108 - Time - HH:MI:SS
112 - Date - YYYYMMDD
121 - ODBC - YYYY-MM-DD HH:MI:SS.FFF
20 - ODBC - YYYY-MM-DD HH:MI:SS
There are 3 different methods depending on what I is my requirement and which version I am using.
Here are the methods..
1) Using Convert
DECLARE #DateTime DATETIME = GETDATE();
--Using Convert
SELECT
CONVERT(NVARCHAR, #DateTime,120) AS 'myDateTime'
,CONVERT(NVARCHAR(10), #DateTime, 120) AS 'myDate'
,RIGHT(CONVERT(NVARCHAR, #DateTime, 120),8) AS 'myTime'
2) Using Cast (SQL Server 2008 and beyond)
SELECT
CAST(#DateTime AS DATETIME2) AS 'myDateTime'
,CAST(#DateTime AS DATETIME2(3)) AS 'myDateTimeWithPrecision'
,CAST(#DateTime AS DATE) AS 'myDate'
,CAST(#DateTime AS TIME) AS 'myTime'
,CAST(#DateTime AS TIME(3)) AS 'myTimeWithPrecision'
3) Using Fixed-length character data type
DECLARE #myDateTime NVARCHAR(20) = CONVERT(NVARCHAR, #DateTime, 120);
DECLARE #myDate NVARCHAR(10) = CONVERT(NVARCHAR, #DateTime, 120);
SELECT
#myDateTime AS 'myDateTime'
,#myDate AS 'myDate'
You can use the convert statement in Microsoft SQL Server to convert a date to a string. An example of the syntax used would be:
SELECT convert(varchar(20), getdate(), 120)
The above would return the current date and time in a string with the format of YYYY-MM-DD HH:MM:SS in 24 hour clock.
You can change the number at the end of the statement to one of many which will change the returned strings format. A list of these codes can be found on the MSDN in the CAST and CONVERT reference section.
Check CAST and CONVERT syntax of t-sql:
http://msdn.microsoft.com/en-us/library/ms187928.aspx
Try below :
DECLARE #myDateTime DATETIME
SET #myDateTime = '2013-02-02'
-- Convert to string now
SELECT LEFT(CONVERT(VARCHAR, #myDateTime, 120), 10)
This has been answered by a lot of people, but I feel like the simplest solution has been left out.
SQL SERVER (I believe its 2012+) has implicit string equivalents for DATETIME2 as shown here
Look at the section on "Supported string literal formats for datetime2"
To answer the OPs question explicitly:
DECLARE #myVar NCHAR(32)
DECLARE #myDt DATETIME2
SELECT #myVar = #GETDATE()
SELECT #myDt = #myVar
PRINT(#myVar)
PRINT(#myDt)
output:
Jan 23 2019 12:24PM
2019-01-23 12:24:00.0000000
Note:
The first variable (myVar) is actually holding the value '2019-01-23 12:24:00.0000000' as well. It just gets formatted to Jan 23 2019 12:24PM due to default formatting set for SQL SERVER that gets called on when you use PRINT. Don't get tripped up here by that, the actual string in (myVer) = '2019-01-23 12:24:00.0000000'
In the stored procedure for me works something like this.
convert(varchar(10), StartingDate) AS 'StartingDate'

Convert a SQL Server datetime to a shorter date format

I have a datetime column in SQL Server that gives me data like this 10/27/2010 12:57:49 pm and I want to query this column but just have SQL Server return the day month and year - eg. 2010 10 27 or something like that.
What are the functions I should be researching?
Should I be trying to convert to another date data type? Or simply convert it to a string?
Have a look at CONVERT. The 3rd parameter is the date time style you want to convert to.
e.g.
SELECT CONVERT(VARCHAR(10), GETDATE(), 103) -- dd/MM/yyyy format
Try this:
print cast(getdate() as date )
If you need the result in a date format you can use:
Select Convert(DateTime, Convert(VarChar, GetDate(), 101))
In addition to CAST and CONVERT, if you are using Sql Server 2008, you can convert to a date type (or use that type to start with), and then optionally convert again to a varchar:
declare #myDate date
set #myDate = getdate()
print cast(#myDate as varchar(10))
output:
2012-01-17
If you have a datetime field that gives the results like this 2018-03-30 08:43:28.177
Proposed: and you want to change the datetime to date to appear like 2018-03-30
cast(YourDateField as Date)
With SQL Server 2005, I would use this:
select replace(convert(char(10),getdate(),102),'.',' ')
Results: 2015 03 05
The shortest date format of mm/dd/yy can be obtained with:
Select Convert(varchar(8),getdate(),1)
Just add date keyword.
E.g. select date(orderdate),count(1) from orders where orderdate > '2014-10-01' group by date(orderdate);
orderdate is in date time.
This query will show the orders for that date rather than datetime.
Date keyword applied on a datetime column will change it to short date.
For any versions of SQL Server: dateadd(dd, datediff(dd, 0, getdate()), 0)
The original DateTime field : [_Date_Time]
The converted to Shortdate : 'Short_Date'
CONVERT(date, [_Date_Time]) AS 'Short_Date'

Remove time from DateTime sql server 2005

I need date part from datetime. in format of "dd-mm-yyyy"
I have tried follwoing
Query:
select Convert(varchar(11), getdate(),101)
Output:
01/11/2011
Query
SELECT cast(floor(cast(GETDATE() as float)) as datetime)
Output
2011-01-11 00:00:00.000
Query:
SELECT
CONVERT(VARCHAR(MAX),DATENAME(DD,GETDATE())) + '-' +
CONVERT(VARCHAR(MAX),DATEPART(MONTH,GETDATE())) + '-' +
CONVERT(VARCHAR(MAX),DATENAME(YYYY,GETDATE())) `
Output:
11-1-2011 i.e. "d-m-yyyy"
I required output in "dd-mm-yyyy" format.
SELECT CONVERT(VARCHAR(10),GETDATE(),105)
Try:
SELECT convert(varchar, getdate(), 105)
More here.
Here you can find some examples how to do this: http://blog.pengoworks.com/index.cfm/2009/1/9/Useful-tips-and-tricks-for-dealing-with-datetime-in-SQL
Using the CONVERT function "works" but only if you're comparing strings with strings. To compare dates effectively, you really need to keep the SMALLDATETIME data type strongly typed on both side of the equation (ie "="). Therefore 'apros' comment above is really the best answer here because the blog mentioned has the right formulas to use to strip off the time component by "flattening" it to midnight (ie 12:00:00) via rounding and any date column in SQL Server 2005 will always default to 12:00:00 if the date is given without a time.
This worked for me ...
select dateadd(day, datediff(day, '20000101', #date), '20000101')

Resources