简体   繁体   中英

Beginner's question on what to add in a PHP time variable

I found this script on php.net and finds the difference between now and a future day. My question is very simple, but is a sample time or how can I make that time that it is needed for the $future_date ? Also what is the purpose of -1970?

Also how can I show a message when the future_date is reached or passed?

<?php
function time_difference($endtime){
    $days= (date("j",$endtime)-1);
    $months =(date("n",$endtime)-1);
    $years =(date("Y",$endtime)-1970);
    $hours =date("G",$endtime);
    $mins =date("i",$endtime);
    $secs =date("s",$endtime);
    $diff="'day': ".$days.",'month': ".$months.",'year': ".$years.",'hour': ".$hours.",'min': ".$mins.",'sec': ".$secs;
    return $diff;
}   
$end_time = $future_date - time();
$difference = time_difference($end_time);
echo $difference;

//sample output
'day': 2,'month': 1,'year': 0,'hour': 2,'min': 05,'sec': 41

?>

A unix timestamp checkout the docs for time() and mktime()

You're substracting two values from each other so they need to be compatibable formats to be able to do that. Checking the documentation on time() could have saved you from this question.

date() is also a function you might want to check up on. Using date and the right parameters it will return the current year(Y) month(m) or day of the month(d) you can add and substract to these values and then pass them into mktime to get a unix timestamp like so for the current year in unix timestamp format:

$currentyear = mktime(date(Y));

$future_date should be a unix timestamp.

$future_date = strtotime("next week");

To check if the time has been reached

if($future_date <= time()) echo "Date reached";

$future_date would be an integer timestamp (in seconds since Jan 1, 1970) representing some time in the future.

ie: $nextWeek = time() + (7 * 24 * 60 * 60);

Takes the current date/time and adds 7 days worth of seconds (24 hours, 60 minutes per hour, 60 seconds per minute) to get the integer time of one week from now.

Jan 1, 1970 is significant - it is called the Epoch in UNIX (January 1 1970 00:00:00 GMT) and is often used as a starting point for dates and/or computer "time" (time zero).

Below would set $future_date to 1st Dec 2011

$future_date = mktime(0, 0, 0, 12, 1, 2011);

So Hour Min Sec goes:

$future_date = mktime(H, M, S, 12, 1, 2011);

Below would be 13:21:59 1st Dec 2011

$future_date = mktime(13, 21, 59, 12, 1, 2011);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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