简体   繁体   中英

To convert date format in SQL Server

How can I convert a date present in format 2017-06-30 23:59:59.000 to JUNE 2017 ?

I need to do this using SQL Query.

You can use the FORMAT function for this

SELECT FORMAT(CAST('2017-06-30 23:59:59.000' AS datetime), 'MMMM yyyy');

Result

June 2017

SQL Fiddle

The DATENAME function will return the Name of the month

SELECT DATENAME(month,'2017-06-30 23:59:59.000')+' '+CAST(YEAR('2017-06-30 23:59:59.000') AS VARCHAR) 'Month Name'
SELECT DATENAME(mm,'2017-06-30 23:59:59.000')+' '+CAST(YEAR('2017-06-30 23:59:59.000') AS VARCHAR) 'Month Name'
SELECT DATENAME(m,'2017-06-30 23:59:59.000')+' '+CAST(YEAR('2017-06-30 23:59:59.000') AS VARCHAR) 'Month Name'

This will return

June 2017

If you want to get it from a table, then replace the table and column name in the below query.

SELECT DATENAME(month,ColumnName)+' '+CAST(YEAR(ColumnName) AS VARCHAR) 'Month Name' 
FROM TabeName

The DATENAME function in sql server returns the name of the month.

SELECT DATENAME(MM, GETDATE()) + ' ' + CAST(YEAR(GETDATE()) AS VARCHAR()) AS 
                                                                   [Month YYYY]

For more information you can refer: http://www.sql-server-helper.com/tips/date-formats.aspx

Here is the best answer for MS SQL.

Create table Test(
SampleDate datetime
)
insert into Test(SampleDate)values('07/20/2021 10:20:05'),('08/21/2021 20:30:11')

Here is your query to get the format

select FORMAT(SampleDate, 'MMMM yyyy') YourFormat from Test
--select FORMAT(SampleDate, 'MM/dd/yyyy hh:mm tt') EditedDate from Test

You can see the output here.

Above query return the following output:

July 2021

August 2021

SELECT DATE_FORMAT(column_name, "%M %Y") as alias_column_name FROM tabel_name

Example

SELECT DATE_FORMAT(created_at, "%M %Y") as created_at FROM tabel1

use sql's DATE_FORMAT(date, format) function.

https://www.w3schools.com/mysql/func_mysql_date_format.asp <- visit this website.

https://www.mssqltips.com/sqlservertip/1145/date-and-time-conversions-using-sql-server/ <- Date and Time Conversions Using SQL Server

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM