Home Backend Development PHP Tutorial PHP date query function practical code

PHP date query function practical code

Jul 25, 2016 am 08:54 AM

  1. date_default_timezone_set('PRC'); //Default time zone

  2. echo "Today:",date("Y-m-d",time()),"
    " ;
  3. echo "Today:",date("Y-m-d",strtotime("18 june 2008")),"
    ";
  4. echo "Yesterday:",date("Y-m-d",strtotime("-1 day ")), "
    ";
  5. echo "Tomorrow:",date("Y-m-d",strtotime("+1 day")), "
    ";
  6. echo "One week later:",date ("Y-m-d",strtotime("+1 week")), "
    ";
  7. echo "One week, two days, four hours and two seconds later:",date("Y-m-d G:H:s",strtotime( "+1 week 2 days 4 hours 2 seconds")), "
    ";
  8. echo "Next Thursday:",date("Y-m-d",strtotime("next Thursday")), "
    ";
  9. echo "Last Monday:".date("Y-m-d",strtotime("last Monday"))."
    ";
  10. echo "One month ago:".date("Y-m-d",strtotime( "last month"))."
    ";
  11. echo "One month later:".date("Y-m-d",strtotime("+1 month"))."
    ";
  12. echo "十After the year: ".date("Y-m-d",strtotime("+10 year"))."
    ";
  13. $a = date("w",time()); //Get today is this week Day of the week
  14. $startweekdate =date("Y-m-d H:i:s",strtotime($today)-($a-1)*24*3600); //Get Monday of this week
  15. $endweekdate =date("Y-m-d H :i:s",strtotime($today)+(7-$a+1)*24*3600); //Get the last day of this week and the first day of next week
  16. $endnextweekdate=date("Y-m-d" ,strtotime($endweekdate)+7*24*3600);//The last day of next week
  17. ?>
  18. $d = time(); //Pending date

  19. $w = date("w",$d); //What day of the week is this day?

  20. $d0 = date("Y-m-d",strtotime("-$w day",$d)); / /Start of week
  21. $d6 = date("Y-m-d",strtotime((6-$w)." day",$d)); //End of week
  22. ?>
  23. $d = time( ); //Pending date
  24. $w = date("w",$d); //What day of the week is this day

  25. $d0 = mktime (0,0,0, date("m"),date("d") - $w,date("Y"));//Start of week

  26. $d0 = mktime (0,0,0,date("m"),date( "d") - $w + 6,date("Y"));//End of week
  27. ?>
  28. $date = time();

  29. $w = date("w",$d);

  30. $d0 = date("Y-m-d",strtotime("-$w day",$date)); //Start of week
  31. $d6 = date("Y-m-d",strtotime ((6-$w)." day",$date)); //End of week
  32. ?>
  33. $date1 = date("Y-m-d",strtotime("Sunday")); //Start of week
  34. $date2 = date("Y-m-d",strtotime("Saturday")); //End of week
  35. $date1 = date("Y-m-d",strtotime("last Sunday")); //Start of last week
  36. $date2 = date(" Y-m-d",strtotime("last Saturday")); //End of last week
  37. //Get the year and month of the system
  38. $tmp_date=date("Ym");
  39. //Cut out the year
  40. $tmp_year=substr($tmp_date ,0,4);
  41. //Cut out the month
  42. $tmp_mon =substr($tmp_date,4,2);
  43. $tmp_nextmnoth=mktime(0,0,0,$tmp_mon+1,1,$tmp_year);
  44. $tmp_forwardmnoth=mktime(0,0,0,$tmp_mon-1,1,$tmp_year);
  45. //Get the next month of the current month
  46. $fm_next_mnoth=date("Ym",$tmp_nextmonth);
  47. //Get The previous month of the current month
  48. $fm_forward_mnoth=date("Ym",$tmp_forwardmonth);
  49. ?>
  50. $d=array("日","一","二","三", "Four","Friday","Saturday");
  51. $whatday="week".$d[date("w",strtotime($today))]; //Get today's day of the week
  52. $time = abs( (strtotime("2008-12-25") - strtotime(date("Y-m-d")))/86400);/Get the number of days difference between two dates
  53. ?>
Copy the code

See 7.3.6 Date and Time Types for a description of the range of values ​​each type has and the valid formats for specifying date and time values.

Here is an example using date functions. Select all records whose date_col value is within the last 30 days:

  1. mysql> SELECT something FROM table
  2. WHERE TO_DAYS(NOW()) - TO_DAYS(date_col) <= 30;
Copy code

DAYOFWEEK(date) Returns the day of the week index of date (1=Sunday, 2=Monday, ...7=Saturday). These index values ​​correspond to the ODBC standard.

  1. mysql> select DAYOFWEEK('1998-02-03');
  2. -> 3
Copy code

WEEKDAY(date) Returns the day of the week index of date (0=Monday, 1=Tuesday, ...6=Sunday).

  1. mysql> select WEEKDAY('1997-10-04 22:23:00');
  2. -> 5
  3. mysql> select WEEKDAY('1997-11-05');
  4. -> 2
Copy code

DAYOFMONTH(date) Returns the day of the month for date, in the range 1 to 31.

  1. mysql> select DAYOFMONTH('1998-02-03');
  2. -> 3
Copy code

DAYOFYEAR(date) Returns the day of the year for date, in the range 1 to 366.

  1. mysql> select DAYOFYEAR('1998-02-03');
  2. -> 34
Copy code

MONTH(date) Returns the month of date, ranging from 1 to 12.

  1. mysql> select MONTH('1998-02-03');
  2. -> 2
Copy code

DAYNAME(date) Returns the day of the week name for date.

  1. mysql> select DAYNAME("1998-02-05");
  2. -> 'Thursday'
Copy code

MONTHNAME(date) Returns the month name of date.

  1. mysql> select MONTHNAME("1998-02-05");
  2. -> 'February'
Copy code

QUARTER(date) Returns the quarter of the year for date, ranging from 1 to 4.

  1. mysql> select QUARTER('98-04-01');
  2. -> 2
Copy code

WEEK(date) ​ WEEK(date,first) For places where Sunday is the first day of the week, there is a single argument that returns the week number of the date, in the range 0 to 52. The 2 argument form WEEK() allows You specify whether the week starts on Sunday or Monday. If the second parameter is 0, the week starts on Sunday, if the second parameter is 1, Starting on Monday. &Mysql & GT; Select Week ('1998-02-20');

& GT; 7
Mysql & GT; Select week ('1998-02-20', 0); & gt; 7
Mysql & GT; select WEEK('1998-02-20',1);
    -> 8
  1. Copy code
  2. YEAR(date) Returns the year of date, ranging from 1000 to 9999.
mysql> select YEAR('98-02-03');

-> 1998

Copy code
  1. HOUR(time) Returns the hour of time, ranging from 0 to 23.
mysql> select HOUR('10:05:03');

-> 10

Copy code
  1. MINUTE(time) Returns the minute of time, ranging from 0 to 59.
mysql> select MINUTE('98-02-03 10:05:03');

-> 5

Copy code
  1. SECOND(time) Returns the number of seconds of time, ranging from 0 to 59.
mysql> select SECOND('10:05:03');

-> 3

Copy code
  1. PERIOD_ADD(P,N) Add N months to phase P (in format YYMM or YYYYMM). Returns the value in the format YYYYMM. Note that the phase parameter P is not a date value.
mysql> select PERIOD_ADD(9801,2);

-> 199803

Copy code
  1. PERIOD_DIFF(P1,P2) Returns the number of months between periods P1 and P2. P1 and P2 should be in the format YYMM or YYYYMM. Note that the period parameters P1 and P2 are not date values.
mysql> select PERIOD_DIFF(9802,199703);

-> 11

Copy code
  1. DATE_ADD(date,INTERVAL expr type) ​ DATE_SUB(date,INTERVAL expr type) ​ ADDDATE(date,INTERVAL expr type) ​ SUBDATE(date,INTERVAL expr type) These functions perform date operations. As of MySQL 3.22, they are new. ADDDATE() and SUBDATE() are synonyms of DATE_ADD() and DATE_SUB(). In MySQL 3.23, you can use + and - instead of DATE_ADD() and DATE_SUB(). (see example) date is a date specifying the start date DATETIME or DATE value, expr is an expression specifying the interval value added to or subtracted from the start date, expr is a string; it can be A "-" start indicates a negative interval. type is a keyword that specifies how the expression should be interpreted. EXTRACT(type FROM date) function from date Returns the "type" interval. The following table shows how the type and expr parameters are related: type value meaning expected expr format SECOND seconds SECONDS MINUTE minutes MINUTES HOUR time HOURS DAY DAYS MONTH Month MONTHS YEAR YEARS MINUTE_SECOND minutes and seconds "MINUTES:SECONDS" HOUR_MINUTE hours and minutes "HOURS:MINUTES" DAY_HOUR days and hours "DAYS HOURS" YEAR_MONTH Year and month "YEARS-MONTHS" HOUR_SECOND hours, minutes, "HOURS:MINUTES:SECONDS" DAY_MINUTE days, hours, minutes "DAYS HOURS:MINUTES" DAY_SECOND days, hours, minutes, seconds "DAYS HOURS:MINUTES:SECONDS"

    MySQL allows any punctuation delimiter in expr format. Indicates that recommended delimiters are displayed. If the date parameter is a DATE value and your calculation is just Contains the YEAR, MONTH, and DAY components (i.e., no time component), and the result is a DATE value. Otherwise the result is a DATETIME value.

    1. mysql> SELECT "1997-12-31 23:59:59" + INTERVAL 1 SECOND;
    2. -> 1998-01-01 00:00:00
    3. mysql> 997 -12-31";
    4. -> 1998-01-01
    5. mysql> SELECT "1998-01-01" - INTERVAL 1 SECOND;
    6. -> 1997-12-31 23:59:59
    7. mysql> SELECT DATE_ADD ("1997-12-31 23:59:59",
    8. INTERVAL 1 SECOND);
    9. -> 1998-01-01 00:00:00
    10. mysql> SELECT DATE_ADD("1997-12-31 23:59: 59",
    11. INTERVAL 1 DAY);
    12. -> 1998-01-01 23:59:59
    13. mysql> SELECT DATE_ADD("1997-12-31 23:59:59",
    14. INTERVAL "1:1" MINUTE_SECOND );
    15. -> 1998-01-01 00:01:00
    16. mysql> SELECT DATE_SUB("1998-01-01 00:00:00",
    17. INTERVAL "1 1:1:1" DAY_SECOND);
    18. - > 1997-12-30 22:58:59
    19. mysql> SELECT DATE_ADD("1998-01-01 00:00:00",
    20. INTERVAL "-1 10" DAY_HOUR);
    21. -> 1997-12-30 14:00:00
    22. mysql> SELECT DATE_SUB("1998-01-02", INTERVAL 31 DAY);
    23. -> 1997-12-02
    24. mysql> SELECT EXTRACT(YEAR FROM "1999-07-02");
    25. -> 1999
    26. mysql> SELECT EXTRACT(YEAR_MONTH FROM "1999-07-02 01:02:03");
    27. -> 199907
    28. mysql> SELECT EXTRACT(DAY_MINUTE FROM "1999-07-02 01:0 2: 03");
    29. -> 20102
    Copy code

    If you specify an interval value that is too short (excluding the interval expected by the type keyword), MySQL assumes that you omitted the leftmost part of the interval value. For example, If you specify a type of DAY_SECOND, the value expr is expected to have day, hour, minute, and second components. If you specify a value like "1:10", MySQL assumes that the day and hour parts are missing and the values ​​represent minutes and seconds. In other words, "1:10" DAY_SECOND is equivalent to "1:10" MINUTE_SECOND interpretation, which is ambiguous with the way MySQL interprets the TIME value to represent an elapsed time rather than as a time of day. If you use a date that is indeed incorrect, The result is NULL. If you increment MONTH, YEAR_MONTH, or YEAR and the resulting date is greater than the maximum number of days in the new month, the days are adjusted to the maximum number of days in the new month.

    1. mysql> select DATE_ADD('1998-01-30', Interval 1 month);
    2. -> 1998-02-28
    Copy code

    Note that from the previous example the word INTERVAL and type keywords are not case-sensitive. TO_DAYS(date) Given a date, return a number of days (from year 0).

    1. mysql> select TO_DAYS(950501);
    2. -> 728779
    3. mysql> select TO_DAYS('1997-10-07');
    4. -> 729669
    Copy code

    TO_DAYS() Not intended for use with values ​​before the advent of the Gregorian calendar (1582).

    FROM_DAYS(N) Given a number of days N, return a DATE value.

    1. mysql> select FROM_DAYS(729669);
    2. -> '1997-10-07'
    Copy code

    TO_DAYS() is not intended to be used with values ​​before the advent of the Gregorian calendar (1582).

    DATE_FORMAT(date,format) Format the date value according to the format string. The following modifiers can be used in the format string: %M month name (January......December) %W day of the week name (Sunday......Saturday) %D The day of the month with an English prefix (1st, 2nd, 3rd, etc.) %Y year, number, 4 digits %y year, number, 2 digits %a abbreviated day of the week name (Sun......Sat) %d The number of days in the month, number (00……31) %e The number of days in the month, number (0……31) %m month, number (01……12) %c month, number (1……12) %b abbreviated month name (Jan......Dec) %j Number of days in a year (001……366) %H hours (00……23) %k hours (0...23) %h hours (01……12) %I hours (01……12) %l hours (1...12) %i minutes, number (00……59) %r time, 12 hours (hh:mm:ss [AP]M) %T time, 24 hours (hh:mm:ss) %S seconds (00……59) %s seconds (00……59) %p AM or PM %w The number of days in a week (0=Sunday...6=Saturday) %U day of the week (0...52), where Sunday is the first day of the week %u day of the week (0...52), where Monday is the first day of the week %% A literal "%".

    All other characters are copied into the result without interpretation.

    1. mysql> select DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y');
    2. -> 'Saturday October 1997'
    3. mysql> select DATE_FORMAT(' 1997-10-04 22:23:00', '%H:%i:%s');
    4. -> '22:23:00'
    5. mysql> select DATE_FORMAT('1997-10-04 22:23 :00',
    6. '%D %y %a %d %m %b %j');
    7. -> '4th 97 Sat 04 10 Oct 277'
    8. mysql> select DATE_FORMAT('1997-10-04 22: 23:00',
    9. '%H %k %I %r %T %S %w');
    10. -> '22 22 10 10:23:00 PM 22:23:00 00 6'
    Copy the code

    In MySQL3.23, % is required before the format modifier character. In earlier versions of MySQL, % was optional.

    TIME_FORMAT(time,format) This is used like the DATE_FORMAT() function above, but the format string can only contain those format modifiers that handle hours, minutes, and seconds. Other modifiers produce a NULL value or 0. CURDATE() ​ CURRENT_DATE Returns today's date value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or numeric context.

    1. mysql> select CURDATE();
    2. -> '1997-12-15'
    3. mysql> select CURDATE() + 0;
    4. -> 19971215
    Copy code

    CURTIME() ​ CURRENT_TIME Returns the current time value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or numeric context.

    1. mysql> select CURTIME();
    2. -> '23:50:26'
    3. mysql> select CURTIME() + 0;
    4. -> 235026
    Copy code

    NOW() ​ SYSDATE() ​ CURRENT_TIMESTAMP Returns the current date and time in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function operates on a string or a number context is used.

    1. mysql> select NOW();
    2. -> '1997-12-15 23:50:26'
    3. mysql> select NOW() + 0;
    4. -> 19971215235026
    Copy code

    UNIX_TIMESTAMP() ​ UNIX_TIMESTAMP(date) If called without arguments, returns a Unix timestamp (number of seconds since '1970-01-01 00:00:00' GMT). If UNIX_TIMESTAMP() uses a A date parameter is called, which returns the number of seconds since '1970-01-01 00:00:00' GMT. date can be a DATE string or a DATETIME A string, a TIMESTAMP, or a number of local time in YYMMDD or YYYYMMDD format. mysql> select UNIX_TIMESTAMP();

    1. -> 882226357
    2. mysql> select UNIX_TIMESTAMP('1997-10-04 22:23:00');
    3. -> 875996580
    Copy code

    When UNIX_TIMESTAMP is used for a TIMESTAMP column, the function will accept the value directly, without the implicit "string-to-unix-timestamp" transformation.

    FROM_UNIXTIME(unix_timestamp) Returns the value represented by the unix_timestamp parameter in the format 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS, depending on whether the function is in a string or is used in a numerical context.

    1. mysql> select FROM_UNIXTIME(875996580);
    2. -> '1997-10-04 22:23:00'
    3. mysql> select FROM_UNIXTIME(875996580) + 0; -> 19971004222300
    Copy Code

    FROM_UNIXTIME(unix_timestamp,format) Returns a string representing a Unix timestamp, formatted according to the format string. format can contain the items listed with the DATE_FORMAT() function the same modifiers.

    1. mysql> select FROM_UNIXTIME(UNIX_TIMESTAMP(),
    2. '%Y %D %M %h:%i:%s %x');
    3. -> '1997 23rd December 03:43:30 x '
    Copy code

    SEC_TO_TIME(seconds) Returns the seconds parameter, converted to hours, minutes, and seconds. The value is formatted in 'HH:MM:SS' or HHMMSS, depending on whether the function is in a string or a number. used in context.

    1. mysql> select SEC_TO_TIME(2378);
    2. -> '00:39:38'
    3. mysql> select SEC_TO_TIME(2378) + 0;
    4. -> 3938
    Copy code

    TIME_TO_SEC (time) Return the time parameter, converted to seconds.

    1. mysql> select TIME_TO_SEC('22:23:00');
    2. -> 80580
    3. mysql> select TIME_TO_SEC('00:39:38');
    4. -> 2378
    Copy code


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

Explain the difference between self::, parent::, and static:: in PHP OOP. Explain the difference between self::, parent::, and static:: in PHP OOP. Apr 09, 2025 am 12:04 AM

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

See all articles