Thursday, January 17, 2008

Getting Time part only from SQL DateTime Value

Have you tried getting the time value only from a SQL DateTime value?

I have seen many people struggling with datetime fields in their programming life. Some people face problems getting the date only from datetime field. If you are one who is struggling please read my article on April 2007.

In this article I would like to mention how you can get the time only from a datetime value.

SELECT CAST(CAST(GETDATE() AS FLOAT) - FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME)

Here what I am doing is simply casting the datetime value returned by GETDATE() into FLOAT then I am substracting the full value (value without the fractions) from that. So I will get the fraction part of the float value.

Note that when you cast a datetime value to a float, the full part represents the date and the fraction part represents the time.

2008-01-18 18:22:15.640
39463.7654587963

Then I will cast the result back to the datetime which brings me the time.

This method of casting datetime value to a float value is always handy when working with datetime values.

Friday, January 04, 2008

Inserting a Double Quote in to a String in .NET

Even though this is not new I do forget this always, so thought of putting an entry on how we can put a double quote inside of a string.

VB.NET
Dim str As String = "Example String " & """" & "This is the String with double quotes." & """"
MessageBox.Show(str)

In VB.Net you can indicate that there is a double quote in a string by using 4 double quotes ("""").

C#.NET
string str = "Example String " + "\"" + "This is the String with double quotes." + "\"";
MessageBox.Show(str);

As you will notice in C# the double quote can be represented as double quote, back slash and again using two double quotes ("\"").

The above string will be displayed as follows.

image