Search code examples
sqlsql-servert-sqldate-formatting

Convert DateTime into desired format in SQL Server


In my project we are migrating from an Oracle database to SQL Server.

In Oracle, to get the required date format, we will use the to_char function - it will return the desired format as we mentioned in the second param:

TO_CHAR(TXNDT,'dd/MM/yyyy hh24:mi:ss')

In SQL Server, the same thing can be achieved like below.

convert(varchar(255), TXNDT, 131)

My problem is: I want to get the date format dd-MM-yyyy hh24:mi:ss

I can do this in Oracle:

TO_CHAR(TXNDT,'dd-MM-yyyy hh24:mi:ss')

But how can I achieve the samething in SQL Server?

Any help will be greatly appreciated!


Solution

  • Use format(). I think this does what you want:

    format(TXNDT,'dd-MM-yyyy HH:mm:ss')
    

    If you need this as a varchar():

    convert(varchar(255), format(TXNDT,'dd-MM-yyyy HH:mm:ss')