convert date yyyy-mm-dd to mmm-yy SQL Server 2016 - sql

I want to convert date yyyy-mm-dd (stored as a date format) to mmm-yy format.
There are no exact matches in the prior questions on the site.
I have tried substrings and convert function, was considering creating a scalar function but its taking me a while and hoping someone has an easy solution.

You can construct the format using string operations:
select left(datename(month, datecol), 3) + '-' + right(datename(year, datecol), 2)
Or using format():
select format(datecol, 'MMM-yy')

Try this
select replace(right(convert(varchar(9), getdate(), 6), 6), ' ', '') asDate

Related

How to change datetime format in query?

My datetime column is in YYYYMMDDHHmmss format. Datasource of Grafana is SQL Server 2014 with read only access (TRIM() not valid).
How could I filter results in my query using Grafana time filter options?
I thought in using $__timeFrom() and $__timeTo(), but Grafana uses 2022-01-21T06:29:28Z format or unixepoch.
My query needs to convert:
2022-01-21T06:29:28Z -> 20220121062928
[EDIT]
Try 1 (it works):
WHERE s.zeitpunkt
BETWEEN
CAST(REPLACE(REPLACE(REPLACE(REPLACE($__timeFrom(), '-', ''), 'T', ''), ':', ''), 'Z', '') AS VARCHAR(25))
AND CAST(REPLACE(REPLACE(REPLACE(REPLACE($__timeTo(), '-', ''), 'T', ''), ':', ''), 'Z', '') AS VARCHAR(25))
Try 2 (it does not work):
WHERE s.zeitpunkt
BETWEEN CONCAT(
CONVERT(varchar, $__timeFrom(), 112)
, REPLACE(CONVERT(varchar, $__timeFrom(),108),':','')
)
AND CONCAT(
CONVERT(varchar, $__timeTo(), 112)
, REPLACE(CONVERT(varchar, $__timeTo(),108),':','')
)
If you are having trouble with date format of sql server you can do a number of things to change date format. For Example SSMS and SQL Server date format are decided by Your language and region set
You can use CAST(),CONVERT() to change the format of date or set your format from ssms.
You Can follow this link Date and Time Format in SQL
for datetime to datetimewith different formats
set language 'British'
cast(convert(varchar, getdate(), 103) as datetime)
This will change 2022-01-24 00:38:54.840 to 24/01/2022
This is what finally worked:
I Casted the datetime and used FORMAT() with a custom format. The other solutions I tried where a little bit slower.
WHERE s.zeitpunkt
BETWEEN
CAST(
FORMAT(CAST($__timeFrom() AS DATETIME),'yyyyMMddHHmmss')
AS VARCHAR)
AND CAST(
FORMAT(CAST($__timeTo() AS DATETIME),'yyyyMMddHHmmss')
AS VARCHAR)

How to write a query to select data with a date format 'DD-MMM-YYYY'?

I want to write a query in SELECT statement with the format 'DD-MMM-YYYY' eg:
'1-Jan-2019' or '23-Mar-2018'
Simply
SELECT CONVERT(VARCHAR, GetDate(), 106)
Returns:
23 Jan 2019
See CAST and CONVERT where the Date and Time Styles
If you really want to return '-' separator, you can do as
SELECT REPLACE(CONVERT(VARCHAR, GetDate(), 106), ' ', '-')
Returns:
23-Jan-2019
You can leverage T-SQL FORMAT() to request exact format of the output and culture as you require:
SELECT FORMAT(GETDATE(), '%d-MMM-yyyy', 'en')
It is available since SQL Server 2012
However, better practice is to control format on an app level
If you drop the dashes e.g. '1 jan 2018' then that works out of the box. It is also a really nifty format that always works if you don't know the database settings.
Just remember that month names are abbriviated differently for different languages.
You can do that pretty easily with a Convert call in SQL to a numbered format. It will be close to what you want, but for your format exactly you will need to replace the spaces in the string with dashses by using a Replace call on the result of the convert.
Reference: https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-2017
Example:
select REPLACE(CONVERT(VARCHAR(20), GetDate(), 106), ' ', '-')

SQL convert datetime to varchar

I want to convert DATETIME to VARCHAR (month/day/year) like this:
10/09/2018 12:00:00.000
I tried using
Convert(VARCHAR(MAX),[Date & Time Added]),121)
but it returns
yyyy-mm-dd hh:mi:ss.mmm
I need the / format with time, I am Using SQL Server 2012.
You can use the FORMAT function:
SELECT FORMAT(GETDATE(), 'MM/dd/yyyy HH:mm:ss.fff')
-- 10/09/2018 00:58:52.557
Complete list of format specifiers is actually available in the .NET documentation.
If FORMAT function is unavailable you could simply format in a known format and use string functions to re-arrange the year, month, day and time parts. For example:
SELECT SUBSTRING(DateStr, 6, 2) + '/' + SUBSTRING(DateStr, 9, 2) + '/' + SUBSTRING(DateStr, 1, 4) + ' ' + SUBSTRING(DateStr, 12, 12)
FROM (
SELECT CONVERT(VARCHAR(23), GETDATE(), 126) -- ISO8601 / yyyy-mm-ddThh:mi:ss.mmm
) AS CA(DateStr)
-- 10/09/2018 01:12:50.833
SELECT CONVERT(VARCHAR(10), Date, 101) + ' ' + CONVERT(VARCHAR(12), Date, 114)
FROM (
SELECT GETDATE()
) AS CA(Date)
-- 10/09/2018 01:19:38:463
This is something that would usually be done in the presentation layer, but if you need to do it in the data layer you can use FORMAT (documentation here)
Syntax is: FORMAT ( value, format [, culture ] )
So in your case (edited to add AM/PM designation per your comments): FORMAT([Date & Time Added], 'dd/MM/yyy hh:mm:ss.fff tt')
Custom date format string options are detailed here

DATENAME and DATEPART in SQL

I'm trying to get my EntryDate column in this format 'YYYY_m' for example '2013_04'.
This code has been unsuccessful
DATENAME (YYYY, EntryDate) + '_' + DATEPART (M, EntryDate)
Attempts using DATEFORMAT have also been unsuccessful, stating there was syntax error at ',' after the M. What code would work instead?
Thank you.
How about date_format()?
select date_format(EntryDate, '%&Y_%m')
This is the MySQL way. Your code looks like an attempt to do this in SQL Server.
EDIT:
The following should work in SQL Server:
select DATENAME(year, EntryDate) + '_' + RIGHT('00' + DATEPART(month, EntryDate), 2)
Personally, I might use convert():
select replace(convert(varchar(7), EntryDate, 121), '-', '_')
select DATENAME (YYYY, EntryDate)
+ '_'
+ right('0' + convert(varchar(2),datepart (MM, EntryDate)), 2)
You have to convert the result of DATEPART() to a character string in order for the + to perform an append.
FYI - in the future "unsuccessful" doesn't mean anything. Next time post the actual error you are receiving.
For example:
SELECT concat(EXTRACT(YEAR FROM '2015/1/1'), '_',
LPAD(extract(month from '2014/1/1'),2,'0')) AS OrderYear
This uses
concat to combine strings
lpad to place a leading 0 if month is one digit
and uses extract to pick of the part of date needed.
working fiddle
http://sqlfiddle.com/#!2/63b24/8
DATEPART
It is a Datetime function which extract information from date. This function always returns result as integer type.
SELECT DATEPART(month, '2009-01-01 00:00:00:000') as month
it is return "1" as an integer:
DATENAME
It is also another Datetime function which to extract information from date. This function always returns result as varchar
SELECT DATENAME(month, '2009-01-01 00:00:00:000') as month
it is return "January".

What is the best way to write the date in mm-mm-yyyy in SQL

I'd like to return a date from SQL in the following format 2011-12-DEC, 2012-01-JAN, 2012-02-FEB, 2012-03-MAR etc...
Currently I have the below code, but don't think it's the best. It also does not return a 0 in front of the month (i.e. 8 rather than 08)
print CONVERT(VARCHAR(20), DATEPART(yyyy,GETDATE())) + '-'+ CONVERT(VARCHAR(20), DATEPART(mm,GETDATE()))
For SQL Server, something like this
select convert(varchar(8), getdate(),120)
+ convert(varchar(3),datename(month,getdate()))
For Oracle use TO_CHAR and date formatting. For Example
SELECT TO_CHAR(SYSDATE, 'YYYY-DD-MON') FROM DUAL
There is a wide range of possible date format strings
See here.
If you really do want yyyy-mm-mmm then you could get it like so (for SQL server):
select substring(convert(nvarchar, getdate(), 120), 1, 7)
+ '-' +
substring(upper(datename(mm, getdate())), 1, 3)
Consider a DATE_FORMAT function or the like, depending on your RDMS.
Well,
you should use a formatter (eg AS [DD/MM/YYYY] ).
All of them are listed here including your requirement for "month" naming
http://www.sql-server-helper.com/tips/date-formats.aspx
SELECT SUBSTRING(CONVERT(VARCHAR(11), GETDATE(), 113), 4, 8) AS [Mon-YYYY]
would give you Apr-2006
just turn it around as you like.