Convert Integer field Date time to Date Time - sql-server

I am working in SQL Server 2012. My datetime column in a data set looks like this: 1512543210. The column is in int. I want to convert it to something like dd-mm-yyyy hh:mm:ss e.g. 01-01-2019 12:12:12. But I can not do this. I am using following code:
select dateadd(SS, 1512543210, '01/01/1970 00:00:00') as datetime
from sampledb
after execute query i got this.
2017-12-06 00:00:00.0
but i want this format;
06-12-2017 00:00:00

You can use DATEADD to convert UNIX timestamp to DATETIME and FORMAT function to format it:
SELECT FORMAT(DATEADD(SECOND, 1512543210, '19700101'), 'dd-MM-yyyy hh:mm:ss')
-- 06-12-2017 06:53:30
Having said that, Java has DateTimeFormatter class for formatting dates. And timestamps could be used to construct date objects directly.

You can use the CONVERT option
select CONVERT(varchar,dateadd(SS,DateTime,'01/01/1970 00:00:00') ,21) as datetime from sampledb

You can convert it in the database query as stated in comments and at least one other answer, but you can do it in Java, too:
Have a look at this example:
public static void main(String args[]) {
// take the moment represented by the int from the database
Instant instant = Instant.ofEpochSecond(1512543210);
// create a datetime object (modern java api)
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
// create a formatter for the pattern of your choice
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
// then print the datetime using the desired format
System.out.println(ldt.format(dtf));
}
This outputs
06-12-2017 07:53:30
in my IDE, please check that code in yours.
Please note that you don't need to do the DATEADD operation in SQL for this, just fetch the int value from the database by something like resultSet.getInt(...) and pass it to the Instant.ofEpochSeconds(...), it will calculate the time based on "1970-01-01 00:00:00".

Try this..
select FORMAT(dateadd(SS,1512543210,'01/01/1970 00:00:00'), N'MM-dd-yyyy hh:mm:ss')

If you're on an older version of SQL Server, the format function is not available. An alternative is convert with style 105 (Italian) to get the MM-dd-yyyy part. Then you can take the last part of the 120 (odbc canonical) style to get the hh:mm:ss part:
select convert(varchar(30), dateadd(second, 1512543210, '1970-01-01'), 105) + ' ' +
substring(convert(varchar(30), dateadd(second, 1512543210, '1970-01-01'), 20), 12, 8)
-->
06-12-2017 06:53:30
Example at rextester.

Related

Error on converting date time to specific format in SQL Server

I am newbie to SQL Server and facing an issue. I am trying to convert date time which is in yyyy-mm-dd format to dd/mm/yyyy.
Used below code to change the format, which works well if dd <=12 and throws error The conversion of a varchar data type to a datetime data type resulted in an out-of-range value if dd>12
Declare #LastTime datetime
set #LastTime = '2015-06-12 12:08:18.690'
select convert(varchar, #LastTime, 101)
Tried with other output formats (from here) as well but no luck. Is there a way to fix the issue. I am using SQL Server 2008 version. Referred to many posts here but none of them solved the issue.
Thanks in advance.
If you only want to change the Date format try using this:
SET DATE FORMAT DMY
just write it on the screen, select it and execute it,that will allow you to work with DATE types in the format that you want till you close the session. the DATE type will be a String
The error is from set #LastTime = ... not from your select convert(...)
The error is because your current dateformat is dmy (implicitly set by default language)
If you would rather just change your dateformat then set dateformat mdy; will allow you to set #LastTime with the string 2016-06-13 (June 13th 2016).
If you don't want to mess with changing your dateformat you can specify the style of the string you use with convert when you are setting #LastTime, in this case that would be 121 (120 works as well).
rextester: http://rextester.com/CWZP33091
try this:
declare #LastTime datetime;
set #LastTime = convert(datetime,'2015-06-12 12:08:18.690',121);
select convert(varchar, #LastTime, 101);
have a look at the MSDN documentation for cast and convert at https://msdn.microsoft.com/en-us/library/ms187928.aspx
I'd guess that style 103 is the right one for you.
Give it a try with
select convert(varchar, #LastTime, 103)
I don't have the opportunity to check it out right now, as I don't have a MS SQL Server at hand.
As style 101 converts 'mm/dd/yyyy' it's clear why dd>12 causes an error, as convert is trying to convert 'mm' as a month with valid values from 1 - 12 and you provide 'dd' from 1-31.
Hope that helps
Take care
Andreas

How to extract datetime string SQL Server?

I want a datetime string till minute from Datetime in sql server. Means I want to extract string after minute from Datetime from sql server.
Like: 2011-11-02 13:35:14.613
and I want this from above datetime string -
2011-11-02 13:35
Try this, will give you the date in format yyyy-mm-dd hh:mm as a string.
SELECT CONVERT(CHAR(16),'2011-11-02 13:35:14.613',120)
You can use your column name instead of the static date.
Your problem is a bit tricky, because the default formats which CONVERT() offers do not match your expected output. However, format style 120 has the following format:
yyyy-mm-dd hh:mm:ss
This is almost what you want, minus the :ss at the end. To get rid of that, you can just SUBSTRING() it off after calling CONVERT():
SELECT SUBSTRING(CONVERT(VARCHAR, yourDateColumn, 120), 1, 16)

display current date -1 in sybase

I am trying to display the previous day's date Sybase using a select query:
select dateadd(day,-1,convert(char(10), getdate(), 23))
this query displays as 2015-06-18 00:00:00.0
I expect the output to be 2015-06-18.
How can I get that?
Try select dateadd(day,-1,convert(Date, getdate(), 365))
Try select convert(char(10),dateadd(day,-1, getdate() ), 23 )
Dateadd expects a date parameter as the third argument. In your example you're feeding it a char(10) . Even though implicit conversion from Char->DateTime is supported in Sybase, I would not code to depend on it in this case.
Well, datetime is a binary type. How it is formatted for display is up to you.
getdate() returns a datetime representing the current date/time. And dateadd() returns a datetime or date value, depending on what it started with (in your case, that would be datetime). And when you run your select statement, it's getting converted to a string using the default format configured for your Sybase instance. Hence your results.
In a nutshell, you are:
Converting the datetime value to char(10) to get an ISO 8601 format date string (yyyy-mm-dd).
Converting that back to a datetime value (so the time component is start-of-day)
Subtracting one day.
The easiest way to get what you want (yesterday's date) is this:
dateadd(day,-1, convert(date,getdate()) )
Which, when formatted for display, will come out as something like (depending on the default format configured for your Sybase instance) yyyy-mm-dd.
Or it might come out like November 29, 2015. If you want to ensure that it is an ISO 8601 date representation, you'll need to be explicit about it and cast it a char or varchar, thus:
convert(char(10) , dateadd(day,-1, convert(date,getdate()) ) , 23 )
which leaves you with a char(10) value containing yesterday's date.
If your version of Sybase doesn't support date, you'll have to fall back to what you were doing, but something like this:
convert(char(10) , dateadd(day,-1, getdate() ) , 23 )
You are telling it to give you hh:mm:ss, so that's what you are getting.
The 23 inside the convert is the format code for yyyy-mm-ddTHH:mm:ss There is no code to get yyyy-mm-dd, the closest you can get is 105 (dd-mm-yy) or 110 (mm-yy-dd).
If you need yyyy-mm-dd, then you'll have to convert the date to a string(char or varchar), and truncate the parts you don't want.
Converting Datetime

How to make SQL Server to save datetime with AM/PM format?

I'm trying to make my SQL Server table datetime columns save datetime with AM/PM. How to make SQL Server to save datetime with AM/PM format?
Right now it saves date like this: 2012-01-23 14:47:00.000
Is it possible to save it 2012-01-23 02:47:00.000 PM ??
Or does SQL Server save the date and time in this format (2012-01-23 14:47:00.000) all the time and I need to convert it just on output and input?
Is it even possible to save it in this format (2012-01-23 02:47:00.000 PM)? Or does SQL Server save datetime in 24 hour format?
thanks indeed for any help. sorry for language. ;)
Internally the date and time are stored as a number.
Whether it's displayed in a 12 or 24 hour clock is up to the program formatting it for display.
As Andrew said, Datetime format is stored not as string. so, you can use CONVERT function to get the datetime value in approprate format. for example,
SELECT CONVERT(VARCHAR(20), GETDATE(), 100)
to learn more about datetime formatting, see this article
AM/PM serves only for visualization, if you need to display them, use CONVERT keyword:
SELECT CONVERT(varchar, YourDateTimeField, 109)
FROM YourTable
If you need to store AM/PM - it is makes no sense for datetime type, use varchar type instead.
You can simply use CONVERT function as following:
select CONVERT(VARCHAR,GETDATE(),108)
http://www.fmsinc.com/free/NewTips/SQL/AM_PM_time_format_in_SQL.asp
http://msdn.microsoft.com/en-us/library/Aa226054
http://blogs.msdn.com/b/kathykam/archive/2006/09/29/773041.aspx
Depending on the accuracy of the datetime you are storing you might be able to clean it up with
REPLACE(CONVERT (varchar, YourDateTimeField, 109), ':00.0000000', ' ')
This will not work if your date field is populated with GETDATE() as that means it will contain seconds and milliseconds but it will work if the field is populated by a user and seconds and milliseconds are all zeros

Sql Server string to date conversion

I want to convert a string like this:
'10/15/2008 10:06:32 PM'
into the equivalent DATETIME value in Sql Server.
In Oracle, I would say this:
TO_DATE('10/15/2008 10:06:32 PM','MM/DD/YYYY HH:MI:SS AM')
This question implies that I must parse the string into one of the standard formats, and then convert using one of those codes. That seems ludicrous for such a mundane operation. Is there an easier way?
Try this
Cast('7/7/2011' as datetime)
and
Convert(DATETIME, '7/7/2011', 101)
See CAST and CONVERT (Transact-SQL) for more details.
Run this through your query processor. It formats dates and/or times like so and one of these should give you what you're looking for. It wont be hard to adapt:
Declare #d datetime
select #d = getdate()
select #d as OriginalDate,
convert(varchar,#d,100) as ConvertedDate,
100 as FormatValue,
'mon dd yyyy hh:miAM (or PM)' as OutputFormat
union all
select #d,convert(varchar,#d,101),101,'mm/dd/yy'
union all
select #d,convert(varchar,#d,102),102,'yy.mm.dd'
union all
select #d,convert(varchar,#d,103),103,'dd/mm/yy'
union all
select #d,convert(varchar,#d,104),104,'dd.mm.yy'
union all
select #d,convert(varchar,#d,105),105,'dd-mm-yy'
union all
select #d,convert(varchar,#d,106),106,'dd mon yy'
union all
select #d,convert(varchar,#d,107),107,'Mon dd, yy'
union all
select #d,convert(varchar,#d,108),108,'hh:mm:ss'
union all
select #d,convert(varchar,#d,109),109,'mon dd yyyy hh:mi:ss:mmmAM (or PM)'
union all
select #d,convert(varchar,#d,110),110,'mm-dd-yy'
union all
select #d,convert(varchar,#d,111),111,'yy/mm/dd'
union all
select #d,convert(varchar,#d,12),12,'yymmdd'
union all
select #d,convert(varchar,#d,112),112,'yyyymmdd'
union all
select #d,convert(varchar,#d,113),113,'dd mon yyyy hh:mm:ss:mmm(24h)'
union all
select #d,convert(varchar,#d,114),114,'hh:mi:ss:mmm(24h)'
union all
select #d,convert(varchar,#d,120),120,'yyyy-mm-dd hh:mi:ss(24h)'
union all
select #d,convert(varchar,#d,121),121,'yyyy-mm-dd hh:mi:ss.mmm(24h)'
union all
select #d,convert(varchar,#d,126),126,'yyyy-mm-dd Thh:mm:ss:mmm(no spaces)'
In SQL Server Denali, you will be able to do something that approaches what you're looking for. But you still can't just pass any arbitrarily defined wacky date string and expect SQL Server to accommodate. Here is one example using something you posted in your own answer. The FORMAT() function and can also accept locales as an optional argument - it is based on .Net's format, so most if not all of the token formats you'd expect to see will be there.
DECLARE #d DATETIME = '2008-10-13 18:45:19';
-- returns Oct-13/2008 18:45:19:
SELECT FORMAT(#d, N'MMM-dd/yyyy HH:mm:ss');
-- returns NULL if the conversion fails:
SELECT TRY_PARSE(FORMAT(#d, N'MMM-dd/yyyy HH:mm:ss') AS DATETIME);
-- returns an error if the conversion fails:
SELECT PARSE(FORMAT(#d, N'MMM-dd/yyyy HH:mm:ss') AS DATETIME);
I strongly encourage you to take more control and sanitize your date inputs. The days of letting people type dates using whatever format they want into a freetext form field should be way behind us by now. If someone enters 8/9/2011 is that August 9th or September 8th? If you make them pick a date on a calendar control, then the app can control the format. No matter how much you try to predict your users' behavior, they'll always figure out a dumber way to enter a date that you didn't plan for.
Until Denali, though, I think that #Ovidiu has the best advice so far... this can be made fairly trivial by implementing your own CLR function. Then you can write a case/switch for as many wacky non-standard formats as you want.
UPDATE for #dhergert:
SELECT TRY_PARSE('10/15/2008 10:06:32 PM' AS DATETIME USING 'en-us');
SELECT TRY_PARSE('15/10/2008 10:06:32 PM' AS DATETIME USING 'en-gb');
Results:
2008-10-15 22:06:32.000
2008-10-15 22:06:32.000
You still need to have that other crucial piece of information first. You can't use native T-SQL to determine whether 6/9/2012 is June 9th or September 6th.
SQL Server (2005, 2000, 7.0) does not have any flexible, or even non-flexible, way of taking an arbitrarily structured datetime in string format and converting it to the datetime data type.
By "arbitrarily", I mean "a form that the person who wrote it, though perhaps not you or I or someone on the other side of the planet, would consider to be intuitive and completely obvious." Frankly, I'm not sure there is any such algorithm.
Use this:
SELECT convert(datetime, '2018-10-25 20:44:11.500', 121) -- yyyy-mm-dd hh:mm:ss.mmm
And refer to the table in the official documentation for the conversion codes.
For this problem the best solution I use is to have a CLR function in Sql Server 2005 that uses one of DateTime.Parse or ParseExact function to return the DateTime value with a specified format.
Short answer:
SELECT convert(date, '10/15/2011 00:00:00', 101) as [MM/dd/YYYY]
Other date formats can be found at SQL Server Helper > SQL Server Date Formats
Took me a minute to figure this out so here it is in case it might help someone:
In SQL Server 2012 and better you can use this function:
SELECT DATEFROMPARTS(2013, 8, 19);
Here's how I ended up extracting the parts of the date to put into this function:
select
DATEFROMPARTS(right(cms.projectedInstallDate,4),left(cms.ProjectedInstallDate,2),right( left(cms.ProjectedInstallDate,5),2)) as 'dateFromParts'
from MyTable
The most upvoted answer here are guravg's and Taptronic's. However, there's one contribution I'd like to make.
The specific format number they showed from 0 to 131 may vary depending on your use-case (see full number list here), the input number can be a nondeterministic one, which means that the expected result date isn't consistent from one SQL SERVER INSTANCE to another, avoid using the cast a string approach for the same reason.
Starting with SQL Server 2005 and its compatibility level of 90,
implicit date conversions became nondeterministic. Date conversions
became dependent on SET LANGUAGE and SET DATEFORMAT starting with
level 90.
Non deterministic values are 0-100, 106, 107, 109, 113, 130. which may result in errors.
The best option is to stick to a deterministic setting, my current preference are ISO formats (12, 112, 23, 126), as they seem to be the most standard for IT people use cases.
Convert(varchar(30), '210510', 12) -- yymmdd
Convert(varchar(30), '20210510', 112) -- yyyymmdd
Convert(varchar(30), '2021-05-10', 23) -- yyyy-mm-dd
Convert(varchar(30), '2021-05-10T17:01:33.777', 126) -- yyyy-mm-ddThh:mi:ss.mmm (no spaces)
This page has some references for all of the specified datetime conversions available to the CONVERT function. If your values don't fall into one of the acceptable patterns, then I think the best thing is to go the ParseExact route.
Personally if your dealing with arbitrary or totally off the wall formats, provided you know what they are ahead of time or are going to be then simply use regexp to pull the sections of the date you want and form a valid date/datetime component.
If you want SQL Server to try and figure it out, just use CAST
CAST('whatever' AS datetime)
However that is a bad idea in general. There are issues with international dates that would come up. So as you've found, to avoid those issues, you want to use the ODBC canonical format of the date. That is format number 120, 20 is the format for just two digit years.
I don't think SQL Server has a built-in function that allows you to provide a user given format. You can write your own and might even find one if you search online.
convert string to datetime in MSSQL implicitly
create table tmp
(
ENTRYDATETIME datetime
);
insert into tmp (ENTRYDATETIME) values (getdate());
insert into tmp (ENTRYDATETIME) values ('20190101'); --convert string 'yyyymmdd' to datetime
select * from tmp where ENTRYDATETIME > '20190925' --yyyymmdd
select * from tmp where ENTRYDATETIME > '20190925 12:11:09.555'--yyyymmdd HH:MIN:SS:MS
You can easily achieve this by using this code.
SELECT Convert(datetime, Convert(varchar(30),'10/15/2008 10:06:32 PM',102),102)
This code solve my problem :
convert(date,YOUR_DATE,104)
If you are using timestamp you can you the below code :
convert(datetime,YOUR_DATE,104)
dateadd(day,0,'10/15/2008 10:06:32 PM')

Resources