How to format a date store in varchar format - sql

how can i format a date stored in varchar format.
I have saved date in varchar(255) in format dd:mm:yyyy hh:mm:ss. I need to convert or get in the format hh:mm:ss. I do not want to alter the database structure
I tried,
SELECT [FinishingTime] format(varchar(255), [FinishingTime], 120)
In addition to this question:
I would try to alter the database structure. In the Sql database if i use the datetime2(0). Then i have a problem in getting through my groovy code. I have in long i try to convert into dateformat and set in the string and later store in
database.
def time1= time / 1000; here time is in long
def time2 = time1 + 3600 + timeLeft;
LocalDateTime dateTime = LocalDateTime.ofEpochSecond(Finish2, 0, ZoneOffset.UTC);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss", Locale.ENGLISH);
String formattedDate = dateTime.format(formatter);
machine.setFinishingTime(formattedDate);
Now i use the getter and setter in a class.
public String getFinishingTime()
{
return getPropertyContainer().getString(FINISHING_TIME, "")
}
public void setFinishingTime(String finishingTime)
{
getPropertyContainer().setString(FINISHING_TIME, finishingTime)
}
Now the question is if i use date time instead of string it does not write in my database or i am not able to set through setter.

You don't need a conversations just use substring() function :
select substring([FinishingTime], charindex(' ', [FinishingTime]) + 1, len([FinishingTime]))
from table t;
However, your idea is really bad to store date-time in custom format, it will lead you lots of trouble while data querying.

I assume it is MS SQL
select convert(varchar, FinishingTime, 108)
or
select convert(varchar, FinishingTime, 8)

Related

Convert string to datetime in cosmos db

In my cosmos db a date field is stored as string like this
{
"ValidationWeekStartDay": "27-Apr-2020"
}
I have to write a query to extract all documents whose ValidationWeekStartDay is greater than current date. How can I achieve this in cosmos db query?
Select * from c wher c.ValidationWeekStartDay > GetCurrentDateTime ()
this does not give me correct result.
This is the problem with date format, the documents you are storing is in format 'dd-MMM-yyyy' while GetCurrentDateTime() function gets the date in format 'yyyy-mm-dd....'. So when you run the above query, comparison like below happens:
'27-Apr-2020' > '2020-08-17'
It compares the characters one by one and first 2 characters of first value becomes greater than second value. For testing purpose, anything above date 20 will be returned by your query irrespective of any month.
There are 2 ways to resolve this.
Store the date in same format as GetCurrentDateTime() function.
Create a udf like below. You can create your own udf, this is just a sample one based on date format.(pardon the formatting, you can copy and run it as it is)
function formatdatetime(datetime){ datetime = datetime.substring(7,11) + '-' + datetime.substring(3,6) + '-' + datetime.substring(0,2); datetime = datetime.replace('Jan','01'); datetime = datetime.replace('Feb','02'); datetime = datetime.replace('Mar','03'); datetime = datetime.replace('Apr','04'); datetime = datetime.replace('May','05'); datetime = datetime.replace('Jun','06'); datetime = datetime.replace('Jul','07'); datetime = datetime.replace('Aug','08'); datetime = datetime.replace('Sep','09'); datetime = datetime.replace('Oct','10'); datetime = datetime.replace('Nov','11'); datetime = datetime.replace('Dec','12'); return datetime; }
And then use the below query:
select c.stdDates as stdDates from c Where udf.formatdatetime(c.stdDates) > GetCurrentDateTime ()

Change date to string

I have this code
select Key
,CAST(LEFT(CAST(Key as nvarchar(8)),4)+'0101' as int) as YearaFirstKey
FROM DimDt WHERE Key > 0
I need to change this code to string = cStr() , int as cInt(), use substring mid(). But I don't know how. If I print out the code, it shows this:
SELECT [key], CONVERT(varchar(30), CAST([key] as datetime), 103) as strDate
with your format code chosen from
https://www.w3schools.com/sql/func_sqlserver_convert.asp
+++++
your date is in iso format as a string, so it is simple to change it to a date type, then format the date type using built in SQL functions

Convert varchar data to datetime in SQL server when source data is w/o format

How can I convert VARCHAR data like '20130120161643730' to DATETIME ?
CONVERT(DATETIME, '20130120161643730') does not work.
However, CONVERT (DATETIME, '20130120 16:16:43:730') works. I guess it needs data in correct format.
Is there a valid way that can be used to convert to DATETIME directly from unformatted data ?
My solution is :
DECLARE #Var VARCHAR(100) = '20130120161643730'
SELECT CONCAT(LEFT(#Var,8),' ',SUBSTRING(#var,9,2),':',SUBSTRING(#var,11,2),':',SUBSTRING(#var,13,2),':',RIGHT(#Var,3))
It works fine. However, I'm looking for a compact solution.
You can make it a little more compact by not forcing the dashes, and using STUFF instead of SUBSTRING:
DECLARE #Var VARCHAR(100) = '20130120161643730';
SET #Var = LEFT(#Var, 8) + ' '
+ STUFF(STUFF(STUFF(RIGHT(#Var, 9),3,0,':'),6,0,':'),9,0,'.');
SELECT [string] = #Var, [datetime] = CONVERT(DATETIME, #Var);
Results:
string datetime
--------------------- -----------------------
20130120 16:16:43.730 2013-01-20 16:16:43.730
DECLARE #var VARCHAR(100) = '20130120161643730'
SELECT convert(datetime,(LEFT(#var,8)+' '+SUBSTRING(#var,9,2)+':'+SUBSTRING(#var,11,2)+':'+SUBSTRING(#var,13,2)+':'+RIGHT(#var,3)))
The only possible way to convert this type of string to date time is to break it and then convert it to DateTime. Also, Concat doesnt work in MS SQL but "+".
Assuming this format is something you work with regularly, something more compact would be to create a UDF (user defined function) that parses the string into a valid datetime.
So something along the lines of:
create function dbo.ParseDate (#var varchar(max)) returns datetime as
begin
return (convert(datetime,(LEFT(#var,8)+' '+SUBSTRING(#var,9,2)+':'+SUBSTRING(#var,11,2)+':'+SUBSTRING(#var,13,2)+':'+RIGHT(#var,3))))
end
You could then select from that function like this:
select dbo.ParseDate('20130120161643730')
So any code that needed to reference the date would be more compact.

Convert DateTime to Hex equivalent in VB.NET

How do I achieve the same in VB.NET which is so easily done in SQL Server.
SELECT CAST(GETDATE() AS VARBINARY(8)) --GIVES THE CURRENT TIME IN HEX
Now my question is how can I create the same string in VB.NET so that I can compare in SQL Server as such -
SELECT CASE WHEN GETDATE()=CAST(0X00009F5E00D8DF7C AS DATETIME) THEN 'TRUE' ELSE 'FALSE' END -- 0X00009F5E00D8DF7C WILL BE THE VALUE I GET IN VB.NET WHEN I CONVERT IT DATE.NOW() TO HEX
This answer simply addresses conversion of .NET DateTimes to a binary format that is equivalent to SQL Server's datetime datatype, so I believe it is different enough that it warrants a separate answer (I checked here and here to be sure it was ok).
As #Martin Smith pointed out, the binary format of datetime is not simply a number of ticks since a specific point in time.
datetime is stored as 8 bytes, the first 4 bytes being the number of days since 01-01-1900 and the the second 4 bytes being the number of "ticks" since midnight of that day, where a tick is 10/3 milliseconds.
In order to convert a .NET DateTime to an equivalent binary representation, we need to determine the number of days since '01-01-1900', convert that to hex, and then the number of ticks since midnight, which is slightly complicated since a .NET tick is 100ns.
For example:
DateTime dt = DateTime.Now;
DateTime zero = new DateTime(1900, 1, 1);
TimeSpan ts = dt - zero;
TimeSpan ms = ts.Subtract(new TimeSpan(ts.Days, 0, 0, 0));
string hex = "0x" + ts.Days.ToString("X8") + ((int)(ms.TotalMilliseconds/3.33333333)).ToString("X8");
When I ran this code, dt was 9/14/2011 23:19:03.366, and it set hex to 0x00009F5E01804321, which converted to 2011-09-14 23:19:03.363 in SQL Server.
I believe you will always have a problem getting the exact date because of rounding, but if you can use a query where the datetime doesn't have to match exactly, down to the millisecond, this could be close enough.
Edit
In my comment under the first answer I posted, I asked about SQL Server 2008, because the datetime2 data type does store time with an accuracy of 100ns (at least, it does with the default precision), which matches up nicely with .NET. If you are interested in how that is stored at the binary level in SQL Server, see my answer to an older question.
I had to convert some dates in dbscript from SQL Server's hex format string to standard datetime string (for use with TSQL to MySQL script translation). I used some codes I looked up in here and came up with:
static string HexDateTimeToDateTimeString(string dateTimeHexString)
{
string datePartHexString = dateTimeHexString.Substring(0, 8);
int datePartInt = Convert.ToInt32(datePartHexString, 16);
DateTime dateTimeFinal = (new DateTime(1900, 1, 1)).AddDays(datePartInt);
string timePartHexString = dateTimeHexString.Substring(8, 8);
int timePartInt = Convert.ToInt32(timePartHexString, 16);
double timePart = timePartInt * 10 / 3;
dateTimeFinal = dateTimeFinal.AddMilliseconds(timePart);
return dateTimeFinal.ToString();
}
static string HexDateToDateString(string dateHexString)
{
int days = byte.Parse(dateHexString.Substring(0, 2), NumberStyles.HexNumber)
| byte.Parse(dateHexString.Substring(2, 2), NumberStyles.HexNumber) << 8
| byte.Parse(dateHexString.Substring(4, 2), NumberStyles.HexNumber) << 16;
DateTime dateFinal = new DateTime(1, 1, 1).AddDays(days);
return dateFinal.Date.ToString();
}
Maybe not optimized, but shows the idea.
My first inclination is that the clients should not be constructing sql statements to be executed by your data access layer, but assuming you must get something working soon, you might consider using a parameterized query instead.
If you are making method calls from the client(s) to your other application tiers, you can construct a SqlCommand on the client and pass that to the next tier where it would be executed.
VB.NET is not the language I normally use, so please forgive any syntax errors.
On the client:
Dim dateValue As Date = DateTime.Now
Dim queryText As String = "SELECT CASE WHEN GETDATE() = #Date THEN 'True' ELSE 'False' END"
Dim command As SqlCommand = New SqlCommand(queryText)
command.Parameters.AddWithValue("#Date", dateValue)
If you must send a string, you could convert the DateTime to a string on the client and then convert back to a DateTime on the data access tier, using a common format.
On the client:
Dim queryText As String = "SELECT CASE WHEN GETDATE() = #Date THEN 'True' ELSE 'False' END"
Dim dateValue As Date = DateTime.Now
Dim dateString = DateTime.Now.ToString("M/d/yyyy H:mm:ss.fff", DateTimeFormatInfo.InvariantInfo)
Then send both queryText and dateString to the next tier in your application, where it would convert back to Date and again use a parameterized query:
Dim dateValue As Date
Date.TryParseExact(dateString, "M/d/yyyy H:mm:ss.fff", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, dateValue)
Dim command As SqlCommand = New SqlCommand(queryText)
command.Parameters.AddWithValue("#Date", dateValue)
If your clients are in different time zones, you should (as #Martin Smith mentioned) consider using UTC time.
In .NET
Dim dateValue = DateTime.UtcNow
and also in your query, using GETUTCDATE():
Dim queryText As String = "SELECT CASE WHEN GETUTCDATE() = #Date THEN 'True' ELSE 'False' END"

Sql convert date format

I want to convert dateformat from mm/dd/yyyy to yyyy/mm/dd. I want the output in datetime format.
I tried this
convert(datetime,convert(varchar,getdate(),111),123)
but doesn't work. The error is "explicit conversion to datetime not available"
What is the best way to solve this problem? I'm using Sybase.
Try this
select convert(varchar,CAST('12/11/2010' as DateTime),111)
That won't work. The DATETIME data type has its own format that is really the amount of time that has passed since a fixed reference date; if you ask for a DATETIME it will always be returned according to that format.
How it is displayed to an end user is a function of the client. You can use CONVERT to convert it to a string and specify a format for how it is displayed in the string, but then you're returning a string, not a DATETIME. You can return it as a DATETIME (which has no inherent display format), and then it is up to the client application or OS to define how it is formatted for display. In client applications you also typically have formatting functions that display a date/time according to a format you specify. And if you haven't specified it explicitly in an application, then the display of the date/time will typically be defined by the localization settings in the OS.
Basically, there is a difference between the data type - DATETIME - and its representation to end users.
Formatting is something that should be done in the presentation tier not the data tier. However, most vendors, like Sybase, provide the ability to do rudimentary formatting:
Select Cast( Year(GetDate()) As char(4) )
+ '/' + Right( '00' + Cast( Month(GetDate()) As varchar(2) ), 2 )
+ '/' + Right( '00' + Cast( Day(GetDate()) As varchar(2) ), 2 )
Try this query
select (CONVERT(varchar(10), GETDATE(), 120))