Advertisements
Home > SQL Trivia > SQL Trivia – How to convert milliseconds to [hh:mm:ss.ms] format

SQL Trivia – How to convert milliseconds to [hh:mm:ss.ms] format


 
Today for some reporting purpose I need to convert milliseconds to hh:mm:ss.ms format, i.e.

Hours : Minutes : Seconds . Micro-Seconds
 

So, I tried to create query below, of course by taking help from internet, so that I can have a sample code handy for future reference:

DECLARE @MilliSeconds INT
SET @MilliSeconds = 25289706

SELECT CONCAT(
		RIGHT('0' + CAST(@MilliSeconds/(1000*60*60) AS VARCHAR(2)),2), ':',						-- Hrs
		RIGHT('0' + CAST((@MilliSeconds%(1000*60*60))/(1000*60) AS VARCHAR(2)),2), ':',			-- Mins
		RIGHT('0' + CAST(((@MilliSeconds%(1000*60*60))%(1000*60))/1000 AS VARCHAR(2)),2), '.',	-- Secs
		((@MilliSeconds%(1000*60*60))%(1000*60))%1000											-- Milli Secs
) AS [hh:mm:ss.ms]

-- 7 Hrs, 1 minute, 29 seconds and 706 milliseconds


Advertisements
Categories: SQL Trivia Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: