Converting time from datime into INT

  • declare @dte datetime

    Select @dte = GETDATE()

    @dte = 2016-10-31 11:42:51.920

    Is it possible to convert Time (11:42:51.920) into an INT so that it looks like 114257 ?

  • Yes., There's a few different ways, for example:

    SELECT GETDATE() AS CurrentDateTime,

    (DATEPART(HOUR, GETDATE()) * 10000) + (DATEPART(MINUTE, GETDATE()) * 100) + DATEPART(SECOND, GETDATE()) AS CurrentTimeInt

    Thom~

    Excuse my typos and sometimes awful grammar. My fingers work faster than my brain does.
    Larnu.uk

  • /* date included */

    -- A sensible way

    SELECT FORMAT(GETDATE(), 'ddMMyyyyhhmm', 'en-GB')

    -- The Rube Goldberg way

    SELECT LEFT(CAST(REPLACE(CONVERT(VARCHAR, GETDATE(), 103), '/', '') + REPLACE(CONVERT(VARCHAR, GETDATE(), 108), ':', '') AS BIGINT), 12)

    -- The SQL# way. Why not, right?

    SELECT SQL#.Date_Format(GETDATE(),'ddMMyyyyhhmm','en-GB')

    /* just time */

    SELECT LEFT(CAST(REPLACE(CONVERT(VARCHAR, GETDATE(), 108), ':', '') AS INT), 6)

    SELECT FORMAT(GETDATE(), 'hhmmss', 'en-GB')

    SELECT SQL#.Date_Format(GETDATE(),'hhmmss','en-GB')


    My stack: VS2015 ~ C# ~ MSSQL 2014[/url] ~ DevCraft ~ ReSharper ~ DataGrip ~ Linqer[/url]

  • Although format is easy, if you're applying this to a dataset, I heavily recommend against it. You'll find it to be incredibly slow.

    Thom~

    Excuse my typos and sometimes awful grammar. My fingers work faster than my brain does.
    Larnu.uk

  • hoseam (10/31/2016)


    declare @dte datetime

    Select @dte = GETDATE()

    @dte = 2016-10-31 11:42:51.920

    Is it possible to convert Time (11:42:51.920) into an INT so that it looks like 114257 ?

    Now that you have a couple of ways to do this, I have to ask WHY do you want to do this? Just like the mistake that MS made for job history in MSDB, times as INTs are a royal pain to do just about anything with. WHAT are you good folks looking to do with times converted to INTs?

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply