5.8.1 Problem
You want to produce a new date from a given date by replacing parts of its values.
5.8.2 Solution
Use DATE_FORMAT( ) or TIME_FORMAT( ) to combine parts of the existing value with parts you want to replace.
5.8.3 Discussion
The complement of splitting apart a date or time value is synthesizing one from its constituent parts. Techniques for date and time synthesis include using formatting functions (discussed here) and string concatenation (discussed in Recipe 5.9).
Date synthesis often is performed by beginning with a given date, then keeping parts that you want to use and replacing the rest. For example, to find the first day of the month in which a date falls, use DATE_FORMAT( ) to extract the year and month parts from the date and combine them with a day value of 01:
mysql> SELECT d, DATE_FORMAT(d,'%Y-%m-01') FROM date_val; +------------+---------------------------+ | d | DATE_FORMAT(d,'%Y-%m-01') | +------------+---------------------------+ | 1864-02-28 | 1864-02-01 | | 1900-01-15 | 1900-01-01 | | 1987-03-05 | 1987-03-01 | | 1999-12-31 | 1999-12-01 | | 2000-06-04 | 2000-06-01 | +------------+---------------------------+
TIME_FORMAT( ) can be used in a similar way:
mysql> SELECT t1, TIME_FORMAT(t1,'%H:%i:00') FROM time_val; +----------+----------------------------+ | t1 | TIME_FORMAT(t1,'%H:%i:00') | +----------+----------------------------+ | 15:00:00 | 15:00:00 | | 05:01:30 | 05:01:00 | | 12:30:20 | 12:30:00 | +----------+----------------------------+
Using the mysql Client Program
Writing MySQL-Based Programs
Record Selection Techniques
Working with Strings
Working with Dates and Times
Sorting Query Results
Generating Summaries
Modifying Tables with ALTER TABLE
Obtaining and Using Metadata
Importing and Exporting Data
Generating and Using Sequences
Using Multiple Tables
Statistical Techniques
Handling Duplicates
Performing Transactions
Introduction to MySQL on the Web
Incorporating Query Resultsinto Web Pages
Processing Web Input with MySQL
Using MySQL-Based Web Session Management
Appendix A. Obtaining MySQL Software
Appendix B. JSP and Tomcat Primer
Appendix C. References