Exploring Thoughtz..

MS SQL – DateTime related Functions

Posted by: Vijay Dev on: August 24, 2008

Many a times I have come across code snippets that either format a timestamp value for displaying to the user or compare with another timestamp value. Often its much easier to let the database do the same. However, since the database needs to use functions on the columns to do these conversions, indexes on these columns go unused thereby affecting performance.

To display the current time in a user-readable format, say Aug 24 2008 04:25 PM, the SimpleDateFormat class in Java can be used thus :


Timestamp currentTime = new Timestamp(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy hh:mm a");
String currentTimeFormatted = sdf.format(currentTime);
System.out.println(currentTimeFormatted);

On the other hand, this can be easily achieved in a SQL query (MS SQL) :

SELECT CONVERT(CHAR, GETDATE()) AS 'FormattedDate';

The next one is another useful query (again, MS SQL) that I came across recently (for which I am yet to figure out an equivalent Java code !!) – this truncates the time part of the timestamp and makes it 00:00:00.000 in order to represent the midnight of that particular day.

SELECT CAST( FLOOR( CAST(GETDATE() AS FLOAT ) ) AS DATETIME) AS 'DateTimeAtMidnight';

2 Responses to "MS SQL – DateTime related Functions"

If possible change your feed settings to contain the entire post. It is a lot easier to read a blog off of the feed reader than going to the website to read.

Leave a Reply

Blog Stats

  • 22,312 Visitors

  • Yann: Hello! Could you expand your example for the a bit not-so-hapy java users like me, and describe how to compile and run your code? That would be awesom
  • Anuraj Pandey: Some one is mis-using my id..i got the notification of the above comment..however i havent posted the comment :(
  • Anuraj Pandey: if u have some kind of pdf/text of the material u removed..it will be highly appreciable if u help me..i have my first google intern telephonic interv

My Tweets

About Me

Journey so far…