简体   繁体   中英

How to convert the date format in SQL Server?

I have a table that contains date and the format is :'01-16-1989' which is mm-dd-yyyy but I want to insert to another table that has format like this: '1989-01-16' which is yyyy-mm-dd. What function can I use in the insert statement to do this?

insert into des_table
select date from source_table

How to update the second line in order to finish the date format conversion?

You can convert a string from mm-dd-yyyy format to a date using conversion type 110:

select convert(date, [date], 110) 
from source_table

You can then convert this back to a string in the yyyy-mm-dd format using code 120:

select convert(varchar(10), convert(date, [date], 110), 121)

You can format date with DATE_FORMAT() This is one way SELECT DATE_FORMAT(date, '%Y-%m-%d') FROM source_table;

Source: http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_date-format

Unless they are not actually datetime data types, your insert should be golden as it is.

Also, to answer this you should tell us what RDBMS you are using.

If you are using MySQL this should get you covered:

select DATE_FORMAT(current_date,'%y/%m/%d');

On the dates note you should keep all your dates ISO formated

Since your column is already a DATE you don't need to do any conversions on the insert. If you want it to look a certain way in a specific query result, you can use CONVERT. There are many format options, but again, you don't need to bother with changing how it looks on the insert.

Here are some resources

https://msdn.microsoft.com/en-us/library/ms187928.aspx

https://technet.microsoft.com/en-us/library/ms187928(v=sql.105).aspx

http://www.w3schools.com/sql/func_convert.asp

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