首页 文章资讯内容详情

在MySQL中使用DATE_FORMAT()和STR_TO_DATE()格式化日期

2026-06-04 1 花语

让我们首先创建一个表-

create table DemoTable ( DueDate varchar(100) );

使用插入命令在表中插入一些记录-

insert into DemoTable values(August 04,2019);

使用select语句显示表中的所有记录-

select *from DemoTable;

这将产生以下输出-

+----------------+ | DueDate | +----------------+ | August 04,2019 | +----------------+ 1 row in set (0.00 sec)

以下是格式化日期的查询-

set @stringToDate=(select date_format(str_to_date(DueDate, %M %d,%Y), %Y-%m-%d) from DemoTable);

让我们使用select语句显示日期-

select @stringToDate;

这将产生以下输出-

+---------------+ | @stringToDate | +---------------+ | 2019-08-04 | +---------------+ 1 row in set (0.00 sec)