Calculating time passed since a textual date/time value [duplicate] - php

This question already has answers here:
How to calculate the difference between two dates using PHP?
(34 answers)
Closed 5 years ago.
I have a database from which I extract this date/time value: 2018-01-19 09:50:54
I want to print how many hours and minutes passed since that date, with regard to current server time:
I try this code:
$prev_date = "2018-01-19 09:50:54" // extracted from DB
$date_now = date("Y-m-d H:i:s"); // 24-hour date-time, matches DB format
$interval = $prev_date->diff($date_now); // I saw this on another thread
echo $interval->format('%h')." Hours ".$interval->format('%i')." Minutes";
I get:
Fatal error: Call to a member function diff() on a non-object (on the
$interval=.... line )
I guess it is some kind of formatting problem, how do I fix that?

$prev_date is not a object. You need to transform to a DateTime object to use diff. Also, date() will return a string, you must use a DateTime object for this to be able to use diff function.
$prev_date = DateTime::createFromFormat('Y-m-d H:i:s', '2018-01-19 09:50:54');
$date_now = new DateTime(); // 24-hour date-time, matches DB format
$interval = $prev_date->diff($date_now); // I saw this on another thread
echo $interval->format('%h')." Hours ".$interval->format('%i')." Minutes";

Related

How to format time to "H:i:s" in laravel using carbon [duplicate]

This question already has answers here:
Carbon Difference in Time between two Dates in hh:mm:ss format
(5 answers)
Closed 3 years ago.
I would like to find total time spent on a project given that the user enters the "start time" and "stop time". I have been able to access the time spent but it comes as an array of Date Interval.
I want to just format the results to "H:i:s" (Hour:Minute:Seconds)
Here's the code from my controller
I have already declare the use of Carbon Class(use Carbon/Carbon;) at the top of the controller
$start = Carbon::parse($request->strt_time);
$end = Carbon::parse($request->stp_time);
$time_spent = $end->diff($start);
$spent_time = $time_spent->format('H:i:s');
I expect the output to be 00:00:00 but I am getting a string "H:i:s"
From the Carbon documentation:
Difference
As Carbon extends DateTime it inherit its methods such as diff()
that take a second date object as argument and returns a
DateInterval instance.
We also provide diffAsCarbonInterval() act like diff() but returns
a CarbonInterval instance. Check CarbonInterval chapter for more
information.
So, as Akash suggested, you could do:
$spent_time = $end->diff($start)->format('%H:%i:%s');
Why the % is prefixed in every variable? As #aynber pointed out, the documentation states:
Each format character must be prefixed by a percent sign (%).
Another option is to make use of the gmdate() helper:
$duration = $end->diffInSeconds($start);
$spent_time = gmdate('H:i:s', $duration);
or just:
$spent_time = gmdate('H:i:s', $end->diffInSeconds($start));
diff() method gives CarbonInterval, which inherits the format function from DateInterval. The documentation states that Each format character must be prefixed by a percent sign (%)
DateInterval::format ( string $format ) : string
$january = new DateTime('2010-01-01');
$february = new DateTime('2010-02-01');
$interval = $february->diff($january);
// %a will output the total number of days.
echo $interval->format('%a total days')."\n";
// While %d will only output the number of days not already covered by the
// month.
echo $interval->format('%m month, %d days');
so final solution is
$end->diff($start)->format('%H:%i:%s');

How to get the result of difference between two date using php? [duplicate]

This question already has answers here:
How to get time difference in minutes in PHP
(21 answers)
Closed 5 years ago.
I have this php code
$today_date = date('d/m/Y H:i:s');
$Expierdate = '09/06/2017 21:45:03';
$remaindate = date_diff($today_date,$Expierdate);
echo $remaindate;
and i need result from difference between two date.
date_diff() needs a DateTimeInterface as an argument. In other words, you need to create a DateTime object first, using new DateTime() as shown below.
$today_date = new DateTime();
$Expierdate = new DateTime('09/06/2017 21:45:03');
$remaindate = $today_date->diff($Expierdate);
echo $remaindate->format('%a days');
Live demo
The above would output
90 days
Because today is June 8th, and the format 09/06/2017 is September 6th - because you're using American format (MM/DD/YYYY).
If you ment June 9th (tomorrow), you need to use European format (MM-DD-YYYY, note the dash instead of slash). You can alternatively use DateTime::createFromFormat() to create from a set format, so your current format, 09/06/2017, is interpreted as June 9th. The code would then be
$today_date = new DateTime();
$Expierdate = DateTime::createFromFormat('d/m/Y H:i:s', '09/06/2017 21:45:03');
$remaindate = $today_date->diff($Expierdate);
echo $remaindate->format('%a days');
Output (live demo)
1 days
In any case, $remaindate holds some properties which can be used (see the manual), or you can format it to your liking by supplying the desired formation into the format() method.
new DateTime()
DateTime::diff()
DateTime::format()
DateTime::create_from_format()

DateTime comparison not working PHP [duplicate]

This question already has answers here:
How to compare two time in PHP
(11 answers)
Closed 6 years ago.
timing comparison not working out if passed dynamically
$date = new DateTime();
$date->setTimezone(new DateTimeZone('America/New_York'));
$myTime =$date->format('H:i');
$myDay =$date->format('l');
if(($s<=$myTime) && ($e>=$myTime||$e=="00:00"))
{$open =1;}
Following works if hard coded
if(("11:30"<="05:39")&&("23:00">="05:39"||"23:00"=="00:00"))
{$open =1;}
where m i going wrong
// your first date
$dateA = '2008-03-01 13:34';
// your second date
$dateB = '2007-04-14 15:23';
if(strtotime($dateA) > strtotime($dateB)){
// something here
}
first of all you are using strings to compare time. Convert to timesstamp using strtotime (http://php.net/manual/en/function.strtotime.php) or mktime(http://php.net/manual/en/function.mktime.php) or use DateTime class (http://php.net/manual/en/class.datetime.php). When comparing strings they are not compared as time, but as character sequences.

Convert dd/mm/yyyy to yyyy-mm-dd in php [duplicate]

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 6 years ago.
I need to convert date format in php , But i am getting getting error
here is my code
$test = new DateTime('23/09/2016');
echo date_format($test, 'Y-m-d');
But i am getting error as
Message: DateTime::__construct(): Failed to parse time string (23/09/2016) at position 0 (2): Unexpected character
How to resolve the issue
You're not telling DateTime that what's your string date format. So, it's unable to create a DateTime object.
This should work :
$test = DateTime::createFromFormat('d/m/Y', '23/09/2016');
echo date_format($test, 'Y-m-d');
Read more about createFromFormat here.
Use createFromFormat instead. Like this,
$date = DateTime::createFromFormat('d/m/Y', '23/09/2016');
echo date_format($date, 'Y-m-d');
It's throwing exception because it's unable to parse String to date with / in it.
http://php.net/manual/en/datetime.createfromformat.php
You are getting error because your code is not match with Years and Day.
If you write code below it will work.I just exchange between Years and days .
$test = new DateTime('2016/09/23');
echo date_format($test, 'Y-m-d');
Or you can use createFromFormat to format first date string then convert it in your required format.
$input = "23/09/2016";
$arr = explode("/", $input);
# mktime is a function to create timestamp
# mktime (hour, min, sec, month, day, year)
$mktime = mktime(0,0,0,(int) $arr[1],(int)$arr[0],(int)$arr[2]);
$date1 = date ('d/m/Y', $mktime);
$date2 = date ('Y/m/d', $mktime);
echo "input: $input\ndate1: $date1\ndate2: $date2\n";
or you can try this one, $date2 is the final result.

How to add days to a date with a certain format? [duplicate]

This question already has answers here:
Add number of days to a date
(20 answers)
Closed 7 years ago.
I know this was asked before, but I looked at all those solutions and they don't work for me. Theirs start with a format that I'm not starting with, but even so I tried their solutions anyway and I kept getting a 1970 year as my end date.
So I have a start date in the format of mm-dd-YYYY, and I want to add 35 days to it to create an end date. The following is what I finally was able to make work, but it's inconsistent, or maybe I was wrong and it doesn't really work.
I convert the start date to YYYY-mm-dd because that's what i noticed works better with the strtotime function. I tried converting it differently but nothing worked except doing it the explode way.
So after format conversion then adding the days and converting format back, for some reason it adds like 49 days, even though I am specifying 35 days.
I don't know what else to try.
$startdate = "08-13-2015";
$pieces = explode("-", $startdate);
$newdate = $pieces[2]."-".$pieces[0]."-".$pieces[1];
$enddate = date('m-d-Y', strtotime($newdate. ' + 35 days'));
echo $enddate; //result is 10-01-2015 when it should be 09-17-2015
UPDATE
modified for my need. using variable as the start date.
$inputdate = new DateTime($startdate);
$inputdate->modify('+35 days');
$enddate = $inputdate->format('m-d-Y');
Get the following errors when the page with the code is ran:
Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (08-13-2015) at position 0 (0): Unexpected character' in path\file.php on line 9002
Exception: DateTime::__construct(): Failed to parse time string (08-13-2015) at position 0 (0): Unexpected character in path\file.php on line 9002
9002 says this:
$inputdate = new DateTime($startdate);
DateTime with DateTime::modify() should do it, as shown.
$date = new DateTime('08-13-2015');
$date->modify('+35 days');
echo $date->format('m-d-Y');
But check your PHP version first, if it's below 5.1 you won't be able to use it and under 5.3 you'll face some minor bugs.
you can do it with mktime
$startdate = "08-13-2015";
$pieces = explode("-", $startdate);
$newdate2 = mktime(12, 0, 0, $pieces[0], $pieces[1] + 35, $pieces[2]);
$enddate2 = date('m-d-Y', $newdate2);
var_dump($enddate2); // 09-17-2015
you need to read this
http://php.net/manual/en/book.datetime.php
or use a date library like carbon
https://github.com/briannesbitt/Carbon

Categories