简体   繁体   English

MySQL - 如何将日期转换为具有前导零的月份?

[英]MySQL - How to convert date to the month has leading zeros?

So I'm trying to insert dates into a table and the date is in this format:所以我试图将日期插入表中,日期格式如下:

8/3/2021

However I want to add a leading 0 before the month and day so the date shows 08/03/2021 .但是我想在月份和日期之前添加一个前导 0 ,以便日期显示08/03/2021 Also I want to add it as a string concatenated with another string so test123-08/03/2021另外我想将它添加为与另一个字符串连接的字符串,所以test123-08/03/2021

You should be inserting your source dates into a proper date or datetime columm.您应该将源日期插入到适当的日期或日期时间列中。 Then, to view your dates in the format you want, use the DATE_FORMAT() function with the appropriate format mask:然后,要以所需格式查看日期,请使用DATE_FORMAT() function 和适当的格式掩码:

SELECT DATE_FORMAT(date_col, '%d/%m/%Y') AS date_out
FROM yourTable;

If you really store date in that format then you may try this:如果你真的以这种格式存储日期,那么你可以试试这个:

SELECT 
       DATE_FORMAT(STR_TO_DATE(date_col_string,'%d/%m/%Y'),'%d/%m/%Y') as 'zero-padded',
       CONCAT(string_val,'-',DATE_FORMAT(STR_TO_DATE(date_col_string,'%d/%m/%Y'),'%d/%m/%Y')) as 'concatenated'
FROM mytable;

Use STR_TO_DATE() function to change the date value to standard MySQL date format of YYYY-MM-DD then use DATE_FORMAT() function to display the date value as per your desired output. Use STR_TO_DATE() function to change the date value to standard MySQL date format of YYYY-MM-DD then use DATE_FORMAT() function to display the date value as per your desired output. The second operation is adding CONCAT() function on the converted date with your selected string.第二个操作是使用您选择的字符串在转换后的日期添加CONCAT() function。 I'm assuming that your date value is d/m/y , because as @Stu mentioned in the comment, since you're not storing as MySQL standard date format, that means 8/3/2021 can be either d/m/y or m/d/y .我假设您的日期值是d/m/y ,因为正如评论中提到的@Stu,由于您没有存储为 MySQL 标准日期格式,这意味着8/3/2021可以是d/m/ym/d/y With a standard date format value, the query would be shorter:使用标准日期格式值,查询会更短:

SELECT 
       DATE_FORMAT(date_col,'%d/%m/%Y') as 'zero-padded',
       CONCAT(string_val,'-',DATE_FORMAT(date_col,'%d/%m/%Y')) as 'concatenated'
FROM mytable;

Demo fiddle 演示小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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