SQL Server: How to get current date time in YYYYMMDDHHMISSMSS - sql

I need the current date time in the format YYYYMMDDHHMISSMIS
Example:
20110723233747607
By using the CURRENT_TIMESTAMP or getdate() functions, we can retrieve the current datetime into 2011-07-23 23:37:47.607 format. If I use REPLACE and CONVERT functions to remove the "-" and ":" characters, then I get the value into
Jul 23 2011 11:37PM
...format. But I need the current date time as 20110723233747607 to use it for my another purpose.
My SQL query is:
SELECT REPLACE(CONVERT(VARCHAR(20), CURRENT_TIMESTAMP),'.','')
output: Jul 23 2011 11:37PM
So how can I get the current date time in my required format? Pls help.

select replace(
replace(
replace(
replace(convert(varchar(23), getdate(), 121),
'-',''),
'.',''),
' ',''),
':','')

I do not know why you need to use so many REPLACE() functions. Usage of functions really reduce the execution time. I used two CONVERT and one REPLACE function below.
SELECT CONVERT(VARCHAR(8), GETDATE(), 112) + REPLACE(CONVERT(VARCHAR(12), GETDATE(), 114),':','')

Related

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), ' ', '-')

How to convert string to datetime in SQL

I have done my share in converting string to date in SQL Server 2016 but never seen a date with the format like the one below. I have looked online for a possible way to convert it without success. Any help helping me converting the string below to datetime datatype in SQL will be appreciated.
Fri Aug 24 2018 22:28:40
Regards,
Found a way to do it in SQL Server:
select cast(right("string",20) as datetime) as dateColumn
from table
When dealing with non-standard date formats, I usually lookup CONVERT function in SQL Server, as it io very "elastic": you can provide various formats to it, so it recognizes them appropriately.
I use this site for reference. There you can find, that the closest date format is indicated by 100:
0 100 mon dd yyyy hh:miAM/PM Default
It's your format except it doesn't include unnecessary in this case day of week information. So all you need to do is cut out the Fri part:
substring(myDatetimestring, 5, 1000)
or even better
substring(myDatetimeString, charindex(' ', myDatetimeString), 1000)
if the day of week part may have variable length. Don't worry about 1000, it only assures that we will have the rest of the string, not any less.
Now we have proper date format, since it says that it's default, we don't need to supply 100 to convert function and also we can use cast function instead, as you discovered, so we could do:
cast(substring(myDatetimeString, charindex(' ', myDatetimeString), 1000) as datetime)
or
convert(datetime, substring(myDatetimeString, charindex(' ', myDatetimeString), 1000), 100)
or
convert(datetime, substring(myDatetimeString, charindex(' ', myDatetimeString), 1000))

T-SQL - Convert datetime to unseparated ISO value

I'm trying to convert the following DATETIME into ISO format:
-- Today's Date
2018-04-16 2:04PM
I plan on parsing this into a char value as NVARCHAR so that I can concatenate it as part of a string.
Desired result should be:
-- Date and time unseparated
20180416140422
After some research I discovered here that
CONVERT(datetime, GETDATE(), 112)
using the 112 format code should get me the format I want but somehow I get the following sample output:
--Formatted using 112 format
Apr 16 2018 2:04PM
Why is this? I simply want to format the DATETIME object unseparated.
Also how would I do this with or without the time tagged onto the end?
Using SQL Server 2008R2
It should be :
select CONVERT(varchar(20), GETDATE(), 112)
Output
20180416
If you want date & time both, then can try using this :
select CONVERT(varchar(20), GETDATE(), 112) + replace(CONVERT(varchar(20), GETDATE(), 108), ':', '')
Output
20180416193327
Something like:
--20180416152520
SELECT REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), GETDATE(), 121), '-', ''), ':', ''), ' ', '') AS DesiredFormat
Output:
20180416152520
Check this out:
SELECT CONVERT(varchar(20), GETDATE(), 112) AS ISODate
, CONVERT(varchar(50), GETDATE(), 126) AS ISOWithTime_WorksWithAnyLanguageSetting;
I believe the names of the columns are self-explanatory.
Output example:
ISODate | ISOWithTime_WorksWithAnyLanguageSetting
------------------------------------------------------
20180416 | 2018-04-16T15:26:50.607
For information on more formats of the CONVERT function with examples check this source.
These all seem a bit overly cumbersome when all you need is format():
select format(getdate(), 'yyyyMMddHHmmss') as ISODateTime;

Date Conversion in SQL

I have a date in following format in my DB.
10/16 - mm/yy
I need to convert it to:
October/16
Is this possible?
If it's not possible then please tell me why.
This is not a date, it's missing the day, it's a bad way to store year/month. There should be a 4 digit year to avoid confusion and the year should be listed first to enable correct sorting, e.g. '2016/10' or a numeric value 201610.
You can cast it to a DATE first and then use a FORMAT to disply only month/year:
set dateformat myd;
select format(cast(mystupidcolumn + '/1' as date), 'MMMM/yy')
Or SUBSTR the month part and use a CASE.
try this format,
SELECT DATENAME(month, DATEADD(month, #mydate-1, CAST('2008-01-01' AS datetime)))
You can display date by using this code
select datename(month, YourColumnName) + '/' + right(YEAR(YourColumnName),2)
FROM yourTableName
Simply change yourColumnName with name of your table column and yourTableName with name of table.
Yes you can, and it depend in what database you use to call date functions
If you column Datetime format
SQL server DATENAME(Month, GETDATE())
MySQL database MONTHNAME(now())
otherwise
convert it will in your choice at database or you code logic
split the value and lookup at month enum or fake the date to be accepted and complete date format like 01/10/16
so do something like SELECT DATENAME(Month, datecolumn) + '/' + YEAR (datecolumn)
also you can use instead of Year function DATEPART(yy,datecolumn)
the way you do it with format will look like
CONVERT(VARCHAR(11),GETDATE(),106)
but excepted to get first 3 char of month JUN

SQL Converting string MMM.YY to date

how do i convert/cast a column contains strings e.g. Jan.08,Feb.08.. into date format so that i can sort them?
Greatest Thanks!
I'd just format as a convertible string for the first of the relevant month, and then cast to datetime, e.g.
CAST('1.' + YourMonthAndYearColumnName AS DATETIME)
...is an expression that will yield a datetime that should be sortable, so:
SELECT
YourMonthAndYearColumnName
FROM
YourTable
ORDER BY
CAST('1.' + YourMonthAndYearColumnName AS DATETIME)
...should do what you're looking for.
If you can make the assumption that all dates will be within the last ten years, you can use the following code:
select convert(datetime, replace('Jan.08', '.', ' 20'))
select convert(datetime, replace('Dec.08', '.', ' 20'))
That formats the string into the format "Jan 2008", which is unambiguous. "Dec.08" could be "8th December this year" or "The month of december 2008".
Or you could use Matt Gibson's suggestion of prepending a "1." to your date before conversion. That removes the ambiguity, and has the advantage of using whatever defaults that SQL server has for dates (i.e. 50 is 1950 and 49 is 2049).
select convert(datetime, '1.' + 'Jan.08')
select convert(datetime, '1.' + 'Dec.49')
select convert(datetime, '1.' + 'Jan.50')