How to format datetime in SQL SERVER

0 votes
I am trying to port MySQL function DATE_FORMAT(date,'%y-%m-%d %h:%i:%s %p') to MsSQL equivalent by using CONVERT().
How to format equivalent datetime string in SQL SERVER 2012 to give this output '2014-05-24 01:24:37 AM'?
Sep 17, 2022 in Database by Kithuzzz
• 38,000 points
1,148 views

1 answer to this question.

0 votes

In SQL Server 2012 and up you can use FORMAT():

SELECT FORMAT(CURRENT_TIMESTAMP, 'yyyy-MM-dd hh:mm:ss tt')

For example, in earlier versions you might have needed to concatenate two or more separate DateTime conversions to acquire what you needed:

SELECT 
    CONVERT(CHAR(10), CURRENT_TIMESTAMP, 23) + ' ' + 
    RIGHT('0' + LTRIM(RIGHT(CONVERT(CHAR(20), CURRENT_TIMESTAMP, 22), 11)), 11);

See the Date and Time Styles section of CAST and CONVERT (Transact-SQL) for all of the built-in formatting styles.

If you need to know more about MS SQL, it is recommended to go for the SQL Certification Course today.

answered Sep 18, 2022 by narikkadan
• 63,600 points

Related Questions In Database

0 votes
1 answer

How to delete duplicate rows in SQL Server?

CTEs and ROW_NUMBER can be combined together which will ...READ MORE

answered Feb 10, 2022 in Database by Vaani
• 7,070 points
913 views
0 votes
0 answers

How to update Identity Column in SQL Server?

With 200 records currently, I want to ...READ MORE

Aug 9, 2022 in Database by Kithuzzz
• 38,000 points
1,541 views
0 votes
0 answers

How to ALTER multiple columns at once in SQL Server

ALTER the data types of several columns in ...READ MORE

Aug 12, 2022 in Database by Kithuzzz
• 38,000 points
2,816 views
0 votes
0 answers

How to Create a real one-to-one relationship in SQL Server?

I have two tables, Country and Capital, ...READ MORE

Aug 18, 2022 in Database by Kithuzzz
• 38,000 points
721 views
0 votes
1 answer

How Can I use "Date" Datatype in sql server?

There's problem in all of them and ...READ MORE

answered Feb 9, 2022 in Database by Neha
• 9,020 points
1,471 views
0 votes
1 answer

Difference between datetime and timestamp in sqlserver?

Timestamp is a synonym for rowversion, according ...READ MORE

answered Feb 16, 2022 in Database by Vaani
• 7,070 points
5,126 views
0 votes
1 answer

How to convert DateTime to VarChar

With Microsoft Sql Server: -- -- Create test case -- DECLARE ...READ MORE

answered Feb 23, 2022 in Database by Neha
• 9,020 points
1,323 views
0 votes
1 answer
0 votes
0 answers

How to get Time from DateTime format in SQL?

I want to use a SQL query ...READ MORE

Aug 15, 2022 in Database by Kithuzzz
• 38,000 points
1,002 views
0 votes
0 answers
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP