Can anyone correct the error in my script to calculate the number of days between 2 dates.
The dates have been input through a form, the variable info is as followed:
[departon] => Array ( [0] => 1 [1] => June [2] => 2011 )
[returnon] => Array ( [0] => 31 [1] => June [2] => 2011 )
I have written the code to calculate these dates, but its not calculating the day, it just outputs 0.
<?php
$first_date = mktime(12, 0, 0, $_POST['departon'][1], $_POST['departon'][0], $_POST['departon'][2]);
$second_date = mktime(12, 0, 0, $_POST['returnon'][1], $_POST['returnon'][0], $_POST['returnon'][2]);
$days = $second_date-$first_date;
echo floor($days/60/60/24) . " days";
?>
Help would be much appreciated.
The easiest way is by using datetimes.
Consider this:
var_dump(new DateTime('1 July 2007'));
$a = new DateTime('1 July 2007');
$b = new DateTime('1 June 2001');
var_dump($a->diff($b));
The var_dump will allow you to see the different kind of time you can extract from it.
object(DateInterval)[3]
public 'y' => int 6
public 'm' => int 1
public 'd' => int 0
public 'h' => int 0
public 'i' => int 0
public 's' => int 0
public 'invert' => int 1
public 'days' => int 2221
You can convert your array to a date time very easily by using
$date = new DateTime(join(" ",$array));
$date2 = new DateTime(join(" ",$array2));
$diff = $date->diff($date2);
Here's an easy way:
$depart = strtotime(implode(' ', $_POST['departon']));
$return = strtotime(implode(' ', $_POST['returnon']));
$diff = floor(($return - $depart) / (60 * 60 * 24));
Note: there's only 30 days in June.
The mktime documentation specifies a number for the month, so you'd need to convert 'June' to '6'.
Related
I have an array like so
array (size=5107)
0 => int 421
1 => int 996
2 => int 1555
3 => int 399
4 => int 57914
5 => int 57245
6 => int 7176
7 => int 7166
8 => int 5987
This array is being generated by pulling some timestamps from a database, comparing them and then getting the difference in seconds like so;
$start_date = new DateTime($startdate);
$since_start = $start_date->diff(new DateTime($closedate));
$diff = strtotime($closedate) - strtotime($startdate);
I then want to get the average of the array, but whenever I do a array_sum($array); the result is always negative and I'm not sure why. What am I misunderstanding here?
If I change
$diff = strtotime($closedate) - strtotime($startdate);
To
$diff = strtotime($startdate) - strtotime($closedate);
The array_sum($array); results in a positive value but all the array values are negative but all the results are the same.
You should get the absolute value:
$diff = abs(strtotime($closedate) - strtotime($startdate));
I have a question regarding the date_parse_from_format() method:
$parsed = date_parse_from_format("Y d M H:i T", '2012 28 Nov 21:00 CET');
Returns associative array with detailed info about given date.
This will return an array with some date info. But is there any way to convert it to a unix timestamp?
Johan,
Heres an exact example of how to implement mktime into your scenario:
$parsed = date_parse_from_format("Y d M H:i T", '2012 28 Nov 21:00 CET');
$new = mktime(
$parsed['hour'],
$parsed['minute'],
$parsed['second'],
$parsed['month'],
$parsed['day'],
$parsed['year']
);
echo $new; //returns: 1354136400
For future reference, you can use var_dump() or print_r() on an array to see how to access the nested values.
var_dump of $parsed
array (size=16)
'year' => int 2012
'month' => int 11
'day' => int 28
'hour' => int 21
'minute' => int 0
'second' => int 0
'fraction' => boolean false
'warning_count' => int 0
'warnings' =>
array (size=0)
empty
'error_count' => int 0
'errors' =>
array (size=0)
empty
'is_localtime' => boolean true
'zone_type' => int 2
'zone' => int -60
'is_dst' => boolean false
'tz_abbr' => string 'CET' (length=3)
You can get the UNIX time-stamp by trying to use mktime() for a date.
For Example:
echo mktime(12, 20, 0, 10, 4, 2012 );
You will get the output like that 1349353200
And if you want AM/PM just add 12 to hours if PM.
For Example:
mktime($isAM ? $hrs : ($hrs + 12), $mins, $secs, $m, $d, $y);
and you can also use strtotime():
strtotime() - Parse about any English textual datetime description into a Unix timestamp
echo strtotime("2012-11-03 11:24:00PM");
You will get the output like that 1351985040
In PHP >=5.3, you can use the DateTime constructor which functions exactly like date_parse_from_format. Bonus points: it's a one-liner.
For instance, to convert a date in a UK format to a UNIX timestamp, we can do:
DateTime::createFromFormat("d/m/Y, H:i", '27/03/2020, 22:00')->getTimestamp()
-> int(1585346400)
mktime() should suit your needs perfectly :) Check out http://php.net/manual/en/function.mktime.php to see how you can use it!
I want to calculate the difference between today and next year April 4 (right now is 4/4/2013), but I don't know how to create a DateTime object using actual year + 1. This is what I have:
$now = new DateTime();
$ref = mktime(0, 0, 0, 4, 3, date("Y")+1);
echo $diff = $ref->diff($now)->days;
I think the problem is that mktime is not returning a DateTime object? Which is the best way to do this?
Thanks
$today = date("Y-m-d");
$destination = date("Y-m-d" , mktime(0, 0, 0, 4, 3, date("Y")+1));
$todayObj = new DateTime($today);
$destObj = new DateTime($destination);
echo $diff = $todayObj->diff($destObj)->days;
Didn't test it yet.
Use strtotime for this as below
$nextyear = date('Y')+1;
$time1=$nextyear.'-'.date('m').'-'.date('d');
$time2=date('Y-m-d');
echo $hourdiff = round((strtotime($time1) - strtotime($time2))/3600, 1);
Try this:
print_r(date_diff(date_create(), date_create('2013-04-03 00:00:00')));
Outputs:
DateInterval Object
(
[y] => 0
[m] => 5
[d] => 22
[h] => 9
[i] => 8
[s] => 25
[invert] => 0
[days] => 173
)
Given the information below:
Year: 2012
Weeknumber: 4
Dayname: TUE
How can i convert this to a valid date like 2012-01-12 (YYYY-MM-DD) using PHP's date functions?
Thanx
The DateTime class can't do this, but the function strptime can.
$d = strptime('TUE 4 2012', '%a %W %Y');
var_dump($d);
That returns an array:
array
'tm_sec' => int 0
'tm_min' => int 0
'tm_hour' => int 0
'tm_mday' => int 24
'tm_mon' => int 0
'tm_year' => int 112
'tm_wday' => int 2
'tm_yday' => int 23
'unparsed' => string '' (length=0)
Note that tm_year contains the number of years since 1900 and tm_month is 0-based, not 1-based. So this does represent 2012-01-24, which is correct.
Use this function:
function get_date($year,$week,$day,$start_sunday=false){
$day_array = array('Mon'=>1,'Tue'=>2,'Wed'=>3,'Thu'=>4,'Fri'=>5,'Sat'=>6,'Sun'=>($start_sunday?0:7));
$month_array = array(31,($year%4==0?29:28),31,30,31,30,31,31,30,31,30,31);
$week *= 7;
$month = 1;
for($i=0;$i<count($month_array);$i++){
if($week-$month_array[$i]<=0){
break;
}
$week -= $month_array[$i];
$month++;
}
$format = "$year $month $week";
$date = date_create_from_format("Y m j",$format);
$date_num = date_format($date,"D");
$curr = $day_array[ucfirst(strtolower($day))]-$day_array[$date_num];
$got_date = strtotime("$curr ".($curr==1||$curr==-1?"day":"days"),strtotime(date_format($date,"Y-m-j")));
return $got_date;
}
where $start_sunday should be true if week starts from sunday
$year is the year
$week is week number
$day is short weekday name i.e.mon,tue,wed,....
this function will get you a date form the given format.
Enjoy............
I have a date in the following format
November 18, 2009, 3:00PM
How can i break that up so that i can store each value as its own variable?
such as...
$month //November
$day //18
$year //2009
$hour //03
$minute //00
$ampm //PM
Use the 'date_parse' (http://nl2.php.net/manual/en/function.date-parse.php) function. It returns an array with the parsed items:
Array
(
[year] => 2006
[month] => 12
[day] => 12
[hour] => 10
[minute] => 0
[second] => 0
[fraction] => 0.5
[warning_count] => 0
[warnings] => Array()
[error_count] => 0
[errors] => Array()
[is_localtime] =>
)
Convert your date into a timestamp, then with the timestamp you can easily get your parts. An other way is using a regular expression.
$str = "November 18, 2009, 3:00PM";
list($month,$day,$year,$time) = preg_split('/[ ,]/',$str,false,PREG_SPLIT_NO_EMPTY);
preg_match('/([0-9]+):([0-9]+)([AP]M)/',$time,$timeparts);
list($time,$hour,$minute,$ampm) = $timeparts;
echo "\$month $month\n";
echo "\$day $day\n";
echo "\$year $year\n";
echo "\$hour $hour\n";
echo "\$minute $minute\n";
echo "\$ampm $ampm\n";
Output
$month November
$day 18
$year 2009
$hour 3
$minute 00
$ampm PM
More complex solution.
If your dates may be in the different standards you can use date() function (http://php.net/manual/en/function.date.php) + strtotime() function (http://php.net/manual/en/function.strtotime.php), which parse string and returns the unix timestamp.
For example, if you want to get a year from your date string you could write next code:
$date = 'November 18, 2009, 3:00PM';
$year = date('Y', strtotime($date));
Or, if you want to know how much days in the month in date you get, you could write such code:
$date = 'November 18, 2009, 3:00PM';
$num_of_days = date('t', strtotime($date));
't' returns the number of days in the given month.