Calculate hours difference between today and 4/3/NextYear - php

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
)

Related

Calculate time difference in php

I am trying to calculate time different between 3 different dates
1. Start date
2. End date
3 current date
I have been researching on how to calculation but couldn't find any exact example.
Any assistance in resolving this would be appreciated.
function getweekSartEndDate($date){
$cur_date = strtotime($date); // Change to whatever date you need
// Get the day of the week: Sunday = 0 to Saturday = 6
$dotw = date('w', $cur_date);
if($dotw>1){
$pre_monday = $cur_date-(($dotw-1)*24*60*60);
$next_sunday = $cur_date+((7-$dotw)*24*60*60);
}
else if($dotw==1){
$pre_monday = $cur_date;
$next_sunday = $cur_date+((7-$dotw)*24*60*60);
}
else if($dotw==0){
$pre_monday =$cur_date - (6*24*60*60);;
$next_sunday = $cur_date;
}
$date_array = array();
$date_array['weekStart'] = $pre_monday;
$date_array['weekEnd'] = $next_sunday;
return $date_array;
}
The above is the example code i got so far, and i was able to get the start and end dates of a week as seen below:
$weekStart = date('Y-m-d H:i:s', $weekInfo['weekStart']);
$weekEnd = date('Y-m-d H:i:s', $weekInfo['weekEnd']);
My challenges is how to get the time difference in 'Y-m-d H:i:s' date format from the current time.
You can use
$currentDate = date('Y-m-d H:i:s');
$currentDate = new DateTime($currentDate);
$leaveDate = new DateTime($leaveFrom);
$difference = $currentDate->diff($leaveDate);
You will get result as follow
DateInterval Object ( [y] => 0 [m] => 0 [d] => 0 [h] => 0 [i] => 0 [s] => 0 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => 0 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )
You need basic knowledge on how to do number comparisons in PHP.
Convert your date strings to a UNIX-timestamp with strtotime
$d = strtotime("19/10/2016 14:48:21");
// 1519646232
When the dates are in UNIX-timestamp format, it's easy to compare them with any regular comparison operators as int numbers.
EDIT
Difference in seconds:
$diffBetweenStartAndNow = strtotime( $date_array['weekStart'] ) - time();
$diffBetweenEndAndNow = strtotime( $date_array['weekEnd'] ) - time();

Convert short form month name to month number [duplicate]

This question already has answers here:
PHP convert short month-name to month-number [duplicate]
(7 answers)
Closed 7 years ago.
$month_name = 'Feb';
$month_number = date("m", strtotime($month_name));
From above code, I get the output is 03 not 02. Why?
I suppose it's caused by current date and default value of date in strtotime function. Today we have 31 December so if you use strtotime, default value of date will be 31 Dec 2015, but if you change month to Feb the date will be 03 Mar 2015. Solution here is to add first day number at the begining e.g.
$month_name = '1 Feb';
$month_number = date("m", strtotime($month_name));
You can use the function date_parse():
$month_name = 'Feb';
$date = date_parse($month_name);
echo $date['month'];
what about like this ... simple way ...
$mons = array("Jan" => 1, "Feb" => 2, "Mar" => 3, "Apr" => 4, "May" => 5, "Jun" => 6, "Jul" => 7, "Aug" => 8, "Sep" => 9, "Oct" => 10, "Nov" => 11, "Dec" => 12);
$month_name = 'Feb';
$month_number = $mons[$month_name];
You should pass a full date as follows:
$month_name = 'Feb';
$month_number = date("m", strtotime("1-".$month_name."-2015"));
strtotime will not work like that. You can check in PHP Manual. Here you can use date_parse.
$month = 'Feb';
$month = date_parse($month);
echo $month['month'];
This function will return you an array like:
Array
(
[year] =>
[month] => 2
[day] =>
[hour] =>
[minute] =>
[second] =>
[fraction] =>
[warning_count] => 1
[warnings] => Array
(
[4] => The parsed date was invalid
)
[error_count] => 0
[errors] => Array
(
)
[is_localtime] =>
)
Now, you can get the month name or anything else.
Or, you still want to use strtotime function than you can try it as:
$month = '1 Feb';
$month = date("m",strtotime($month));
echo $month;

Strange behaviour of PHP DateTime Class

I'm trying to get the time difference in milliseconds.
$_SESSION['startTime'] = time();
$to_time = time();
//I call the code from here after a delay, say 4 seconds
$from_time = $_SESSION['startTime'];
$d1 = new DateTime($from_time);
$d2 = new DateTime($to_time);
print_r( $d1->diff($d2));
I print the result after 4 seconds and the result is somewhat like this:
DateInterval Object
(
[y] => 4 //---- Problem, this value should be +
[m] => 0 // |
[d] => 0 // |
[h] => 0 // |
[i] => 0 // |
[s] => 0 //<-here-----------------------------+
[invert] => 1
[days] => 1461
)
[s] should have been 4. why the 4 is in the year section?
What am I doing wrong?
UPDATE - Solved
$to_time = (microtime(true));
$from_time = ( $_SESSION['startTime']);
$diff = $to_time - $from_time;
print $diff;
Prints
3.xxxxxx
You must specify the formatting. You're sending in a unix timestamp into DateTime, therefor:
$d1 = new DateTime($from_time);
$d2 = new DateTime($to_time);
Becomes
$d1 = new DateTime('#'.$from_time);
$d2 = new DateTime('#'.$to_time);
The # symbol tells DateTime that I'm using a Unix Timestamp.
The constructor for DateTime accepts a string as a parameter not a timestamp, which is why you are seeing the "strange behaviour".
You need to expressly set the timestamp after insantiating a DateTime object:-
$from_time = $_SESSION['startTime'];
$d1 = new DateTime();
$d1->setTimestamp($from_time);

Calculate number of days between two given dates

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'.

break apart formatted date into individual month/day/year hour/minute/second in php

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.

Categories