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


Advertisement
Categories: SQL Trivia Tags: ,
  1. Rajat Manik
    April 10, 2020 at 9:18 am

    Syntax error near ‘VARCHAR(2)),2), ‘:’, RIGHT(‘0′ + CAST(((avg(up.modified-up.created))%(100’ at line 5

  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 )

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: