Home Backend Development PHP Tutorial A very comprehensive summary of PHP date and time operations_php skills

A very comprehensive summary of PHP date and time operations_php skills

May 16, 2016 pm 08:05 PM
php date time

Before explaining the examples, let’s introduce a few core functions:
mktime function
The mktime() function returns the Unix timestamp of a date.
The argument always represents a GMT date, so is_dst has no effect on the result.
The parameters can be left empty in order from right to left, and the empty parameters will be set to the corresponding current GMT value.
Syntax: mktime(hour,minute,second,month,day,year,is_dst)
Parameters                                                                                 
hour Optional. Specified hours.
minute Optional. Specified minutes.
second is optional. Specifies seconds.
month is optional. Specifies the numeric month.
day is optional. Specify days.
year is optional. Specified year. On some systems, legal values ​​are between 1901 - 2038. However, this limitation no longer exists in PHP 5.
is_dst Optional. Set to 1 if the time is during Daylight Saving Time (DST), 0 otherwise, or -1 if unknown.
As of 5.1.0, the is_dst parameter is deprecated. Therefore the new time zone handling features should be used.
Example: The mktime() function is useful for date operations and validation. It can automatically correct out-of-bounds input:

<&#63;php 
echo(date("M-d-Y",mktime(0,0,0,12,36,2001))); 
echo(date("M-d-Y",mktime(0,0,0,14,1,2001))); 
echo(date("M-d-Y",mktime(0,0,0,1,1,2001))); 
echo(date("M-d-Y",mktime(0,0,0,1,1,99))); 
&#63;> 
Copy after login
Output:


Jan-05-2002 
Feb-01-2002 
Jan-01-2001 
Jan-01-1999 
Copy after login

strtotime function The
strtotime() function parses any English text datetime description into a Unix timestamp.
Syntax:
strtotime(time,now)
Parameter Description
time specifies the time string to be parsed.
now is the timestamp used to calculate the return value. If this parameter is omitted, the current time is used. 
One week later: strtotime(" 1 week") ;
One week ago: strtotime("-1 week") ;
After one month: strtotime(" 1 months") ;
One day later: strtotime(" 1 days") ;
After 30 seconds strtotime( " 30 seconds " );
After 20 minutes strtotime( " 20 minutes " );
12 hours later strtotime( " 12 hours " );

date function The date() function formats a local time/date.
Grammar
date(format,timestamp)
date_default_timezone_set function
The date_default_timezone_set() function sets the default time zone used for all date/time functions in scripts.
date_default_timezone_set(timezone)

Example

The first case is that there is no database, and if you just compare the obtained date values, you have to use PHP’s time and date function to calculate it, as follows:

For example, to calculate how many days are left from 2015-9-5 to 2015-9-18:


<&#63;php 
$startdate=strtotime("2015-9-5"); 
$enddate=strtotime("2015-9-18"); //上面的php时间日期函数已经把日期变成了时间戳,就是变成了秒。这样只要让两数值相减,然后把秒变成天就可以了,比较的简单,如下: 
$days=round(($enddate-$startdate)/3600/24) ; 
echo $days; //days为得到的天数; 
&#63;> 
Copy after login

The second type Children’s growth

 <&#63; 
date_default_timezone_set('Asia/Shanghai'); 
//以上一句为设置时区,其实不设也行,但是zde debug的时候会有提示,说什么不安全的函数…添上吧。 
 
echo date('Y-m-d H:i:s').' 今天是'.date('Y').'年的第'.date('W').'周'; 
 
$stime='2005-11-03 10:08'; 
echo "<br/><br/>***自出生(<font color=blue>$stime</font>)以来…:<br/><br/>"; 
echo "今天是第<font color=red><b>".Lnbsp(daysofnow($stime),3)."</b></font>天<br/>"; 
echo "今天是第<font color=red><b>".Lnbsp(weeksofnow($stime),3)."</b></font>周<br/>"; 
echo "今天是第<font color=red><b>".Lnbsp(monthsofnow($stime),3)."</b></font>个月<br/>"; 
echo "今天是第<font color=red><b>".Lnbsp(yearsofnow($stime),3)."</b></font>年<br/>"; 
/* 
$output=sprintf(" 今天是第<font color=red><b>%03d</b></font>天<br/>今天是第< font color=red><b>%03d</b></font>周<br/>今天是第< font color=red><b>%03d</b></font>个月<br/>今天是第< font color=red><b>%03d</b></font>年<br/& gt;",daysofnow($stime),weeksofnow($stime),monthsofnow($stime),yearsofnow($stime)); 
echo $output; 
*/ 
 
function weeksofnow($stime) 
{ 
 $ftime=strtotime($stime); 
 $fweeks=date('w',$ftime); 
 if ($fweeks==0) $fweeks=7; 
 $nweeks=date('w'); 
 if ($nweeks==0) $nweeks=7; 
 $ftemp=strtotime(date('Y-m-d 00:00:00',$ftime))-$fweeks*60*60*24; 
 $ntemp=strtotime(date('Y-m-d 00:00:00',time()))+(7-$nweeks)*60*60*24; 
 //echo date('w',$ftemp)."<br/>....<br/>".date('w',$ntemp)."<br/>"; 
 return ($ntemp-$ftemp)/60/60/24/7; 
} 
 
function daysofnow($stime) 
{ 
 $ftime=strtotime($stime); 
 return ceil(abs((time()-$ftime)/(60*60*24))); 
} 
 
function monthsofnow($stime) 
{ 
 $ftime=strtotime($stime); 
 $fmonth=date('m',$ftime); 
 $fyear=date('Y',$ftime); 
 $nmonth=date('m'); 
 $nyear=date('Y'); 
 $result=($nyear-$fyear)*12+$nmonth-$fmonth+1; 
 return $result; 
} 
 
function yearsofnow($stime) 
{ 
 $ftime=strtotime($stime); 
 $fyear=date('Y',$ftime); 
 $nyear=date('Y'); 
 return $nyear-$fyear+1; 
} 
 
// 下面的函数只是加空格用的,不是核心内容,只为美观 
function Lnbsp($data,$num) 
{ 
 $result=trim($data); 
 for($i=$num;$i>=strlen($data);$i--) { 
 $result=' '.$result; 
 } 
 return $result; 
} 
&#63;> 
Copy after login

The third situation: For the dates of tomorrow, next month and next year, you can use the following code:

$tomorrow = date('Y-m-d',mktime (0,0,0,date("m"),date("d")+1,date("Y"))); 
$nextmonth = date('Y-m',mktime (0,0,0,date("m")+1,date("d")+1,date("Y"))); 
$nextyear = date('Y',mktime (0,0,0,date("m"),date("d"),date("Y")+1)); 
 
echo $tomorrow.'<br/>'; 
echo $nextmonth.'<br/>'; 
echo $nextyear.'<br/>'; 
Copy after login

The fourth situation: Working hours (excluding holidays)

<&#63; 
$startDate="2001-12-12"; 
$endDate="2002-11-1"; 
 
$holidayArr=array("05-01","05-02","10-01","10-01","10-02","10-03","10-04","10-05","01-26","01-27","01-28","01-29"); 
 //假期日期数组,比方国庆,五一,春节等 
$endWeek=2; 
 //周末是否双休.双休为2,仅仅星期天休息为1,没有休息为0 
 
$beginUX=strtotime($startDate); 
$endUX=strtotime($endDate); 
 
for($n=$beginUX;$n<=$endUX;$n=$n+86400){ 
 $week=date("w",$n); 
 $MonDay=date("m-d",$n); 
 if($endWeek){//去处周末休息 
 if($endWeek==2){ 
 if($week==0||$week==6) continue; 
 } 
 if($endWeek==1){ 
 if($week==0) continue; 
 } 
 } 
 if(in_array($MonDay,$holidayArr)) continue; 
 $totalHour+=10;//每天工作10小时 
} 
echo "开始日期:$startDate<BR>"; 
echo "结束日期:$endDate<BR>"; 
echo "共花了".$totalHour."小时"; 
&#63;> 
Copy after login


The fifth situation: give seconds to calculate hours

<&#63;php 
function transform($sec){ 
 
 $output = ''; 
 
 $hours = floor($sec / 3600); 
 $remainSeconds = $sec % 3600; 
 
 $minutes = floor($remainSeconds / 60); 
 $seconds = $sec - $hours * 3600 - $minutes * 60; 
 
 if($sec >= 3600){ 
 $output .= $hours.' h / '; 
 $output .= $minutes.' m / '; 
 } 
 
 if($sec >= 60 && $sec < 3600){ 
 $output .= $minutes.' m / '; 
 } 
 
 return $output .= $seconds.' s '; 
} 
 
echo transform(3231803); 
 
&#63;> 
Copy after login
The above are all examples of PHP date and time operations provided for you. I hope it will be helpful to your learning.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to convert date to timestamp in php How to convert date to timestamp in php Mar 24, 2023 am 10:57 AM

When writing programs in PHP, we often need to convert dates to timestamps, or timestamps to dates. This process is very simple in PHP and can be easily accomplished using just a few simple functions. In this article, we'll cover how to convert a PHP date to a timestamp, while also discussing some common usage scenarios.

How to get the current date and day of the week in php How to get the current date and day of the week in php Jan 07, 2023 pm 04:27 PM

In PHP, you can use the date() function to get the current date and day of the week. Just omit the second parameter of the date() function and set the first parameter to "Y-m-d H:i:s" to get the current date, the syntax is "date("Y-m-d H:i:s")"; and When the first parameter is set to "N", the day of the week can be obtained with the syntax "date("N")". "N" returns the day of the week as a number in ISO-8601 format, ranging from 1 (for Monday) to 7 (for Sunday).

How to determine the day of the year based on the year, month and day in php How to determine the day of the year based on the year, month and day in php Apr 22, 2022 pm 05:02 PM

Judgment method: 1. Use the "strtotime("year-month-day")" statement to convert the given year, month and day into timestamp format; 2. Use the "date("z", timestamp)+1" statement to calculate Specifies the day of the year when the timestamp is specified. The number of days returned by date() is calculated from 0, so the real number of days needs to be added to this basis by 1.

How to calculate the difference in months between dates using PHP How to calculate the difference in months between dates using PHP Mar 21, 2023 pm 02:52 PM

Calculating date differences is very common in practical applications. For example, when doing website development, we may need to calculate the difference between two dates in order to correctly display timestamps, countdowns, etc. When calculating the date difference, we often need to calculate the month difference between two dates. Let's introduce how to use PHP to calculate the month difference between dates.

How to convert digital month to English month in php How to convert digital month to English month in php Mar 21, 2023 pm 02:07 PM

In PHP development, we often encounter the situation of converting digital months to English months. This is a common requirement because different countries and languages ​​use different ways of representing months. For example, in the United States and the United Kingdom, people usually use English month names to indicate time, while in France and Germany, people usually use month names in their local languages. This article will introduce how to use PHP to convert month numbers into English month names.

How to convert string to time format in php How to convert string to time format in php Mar 27, 2023 pm 04:16 PM

PHP is a popular programming language that is widely used in web development. Converting between strings and dates is a very common operation in PHP. In this article, we will discuss how to convert PHP string to time format.

How to convert timestamp to time in php How to convert timestamp to time in php Jan 07, 2023 pm 03:17 PM

In PHP, you can use the date() function to convert a timestamp into a date time. This function can format the timestamp into a more readable date and time; the syntax format is "date(format, timestamp)", The format parameter is used to specify the formatting character and set the date format to be converted, such as "Y-m-d H:i:s", which converts the timestamp into the "year-month-day hour:minute:second" format.

How to convert seconds to hours, minutes and seconds in php How to convert seconds to hours, minutes and seconds in php Jun 13, 2022 pm 05:42 PM

In PHP, you can use the date() function to convert seconds into hours, minutes and seconds format, with the syntax "date("H:i:s", timestamp)". The timestamp is the number of seconds since the Unix epoch to the current time, and the date() function can format the timestamp and convert the timestamp into a date string in a specified format through the format character set in the first parameter. The format character "H" represents the 24-hour format, and the "h" character can also be used, which represents the 12-hour format; the format character "i" represents the minutes value with leading zeros, and the format character "s" represents the seconds value with leading zeros.

See all articles