check datetime fails? - php

function is_due($due_date)
{
$now=new DateTime('now');
$dnow=$now->format('Y-m-d');
$due=$due_date->format('Y-m-d');
$interval =(strtotime($dnow)-strtotime($due));
print_r($due_date->format('Y-m-d'));
return $interval;
}
i use that function to check if the given date is due
The $due_date is passed in after being retrieved from an external file as a string '2012-12-12' which is assigned as an array element, for example,
$datetime['due']=ReadExtFile();
When I call that function as print_r(is_due($datetime['due'])); or
$due=new DateTime($datetime['due']);
nothing seems to work, I see no output. But print_r($datetime) will display the result of [due].

The way this method is written, it expects $due_date to be a DateTime object, and not a string. You indicate you are passing in a string and not an object.
It looks like you just want to return $interval as a count of from the date given until now. I would suggest just using a simple method that only deals with strings.
function is_due($due_date) {
return time() - strtotime($due_date);
// return ((time() - strtotime($due_date)) >= 0); // depending on function you want this might work
}

Related

PHP - DateTime::__construct(): Failed to parse time string

I am pulling DateTime timestamp result from another table which is set as:
When dumping specific value of $post->getUploadTime() I get:
"2602585961"
It's in string format.
In my entity I have modified the setter to:
public function setStartTime($startTime)
{
$date = new \DateTime($startTime);
$this->startTime = $date->getTimestamp();
return $this;
}
And my code:
$newEntityObject->setStartTime(intval($post->getUploadTime()));
I am using intval() to transform string to integer (timestamp) so I can insert it in db but I get an error:
DateTime::__construct(): Failed to parse time string (2602585961) at position 8 (6): Unexpected character"
It's an error with or without the intval().
I can not figure out what is wrong?
I know there are a lot of posts about the issue. I tried them, but the problem still remains.
Try :
$date = new \DateTime();
$date->setTimestamp($startTime);
$this->startTime = $date->getTimestamp();
But since you are trying to assign a timestamp to your startTime property and you are already passing a timestamp to your function you can just assign whatever timestamp you are passing:
$this->startTime = $startTime;
You have a timestamp, and you are trying to make it a DateTime and get timestamp from the new datetime object.
The DateTime constructor only accept specific date and time format.
Also, the given value refer to the year 2052. So it's possible that you have another issue before.
You don't need to convert to a number. Because you need a string argument that starts with #
You need use #. Read Documentation.
<?php
$a = "#2602585961";
function setStartTime($startTime)
{
$date = new \DateTime($startTime);
$b = $date->getTimestamp();
return $b;
}
echo setStartTime($a);
https://www.php.net/manual/ru/datetime.formats.compound.php
In your code:
$newEntityObject->setStartTime("#" . $post->getUploadTime());

Carbon in Laravel -- Call to a member function addDay() on integer

I'm trying to build a scheduler in which an incremental day addition and subtraction method is required.
Here, I am simply trying to add a day to this variable (which is displayed to the user elsewhere) each time this function is executed via a button I set up that routes to a certain location. But, I keep getting this error
Call to a member function addDay() on integer
whenever I try to execute this. I am new to using the Carbon interface and looked through the documents, which led me to try parsing the function (worked when I had the same error with a string) but to no avail obviously. Any help is appreciated and/or a possible explanation of how this error is working really.
function addDay(){
$day = (int) Carbon::now()->format('j');
$day = $day->addDay();
}
Thanks in advance. If there is a better way to do this (adding days incrementally with the button/link), I would love to hear it. My logic seems flawed after working on the application the entire day.
You're casting the Carbon date object into an integer by using the (int) in the first $day variable. Therefor when you're trying to access the function addDay() it's failing, because $day is no longer a Carbon object but an integer.
$day = Carbon::now();
$day = $day->addDay()->format('j');
This should work, and if you need to cast it to an integer for some reason, then do it like this.
$day = Carbon::now();
$day = (int) $day->addDay()->format('j');
This way you cast the integer after you've added the day.
There is also a much cleaner approach to this syntax, which uses method chaining like so
$day = (int) Carbon::now()->addDay()->format('j');
As #Classified said but a cleaner approach would be to work with Carbon object first and then apply format on that.
Like this:
$dateObj = Carbon::now()->addDay();
$day = (int) $dateObj->format('j');
Cleaner approach and better readability.
What is the desired returned value ?
$day = Carbon::now()->addDay();
return $day->dayOfWeek; //day of the week, 03/08/18 (now) returns 6 (INT)
return $day->format('j'); //day of the month, 03/08/18 (now) returns "4" (STRING)
return $day->day; //day of the month, 03/08/18 (now) returns 4 (INT)
return $day //Carbon object (at now() + 24h) that you can manipulate
You have to addDay to Carbon instance not to the integer (the day) :
$dt = Carbon::create(2012, 1, 31, 0); // 2012-01-31 00:00:00
echo $dt->addDay(); // 2012-03-04 00:00:00

Call to a member function format() on boolean

I want to find the difference between two dates and I have used date_diff for the same. When format function is applied on date_diff object it returns an error.
Call to a member function format() on boolean
$field_value is fetched from the database and it's format is dd/mm/YYYY. When I hard-code the values for $field_value and $indexing_value the following code works.
Everything is running fine till line number 8. I have tried outputting the value of
$diff->format("%R%a")
and it is returning exact value but the code gives error near the if statement.
$date = new DateTime();
$current_date = $date->format('d/m/Y');
$indexing_value = str_replace("/", "-", $field_value);
$current_value = str_replace("/", "-", $current_date);
$indexing_value = date_create($indexing_value);
$current_value = date_create($current_value);
$diff = date_diff($indexing_value, $current_value);
if ($diff->format("%R%a") < 0) {
echo "1";
} else {
echo "2";
}
Please let me know what is wrong with the above code.
add condition to check whether you got the diff or not, as it returns false if there is error . Check manual for the same
$diff = date_diff($indexing_value, $current_value);
if ($diff) {
if ($diff->format("%R%a") < 0) {
echo "1";
}else{
echo "2";
}
}
You are getting error because for some values the diff is not calculated and have value False in $diff
Please let me know what is wrong with the above code.
There are several issues with the code:
You don't check the values returned by date_create(); it returns FALSE on error.
What's the point of formatting $date then creating $current_value back from the resulting string? If you don't care about the time components and need to use only the date part of a DateTime object you can use its setTime() method to set the time components to 0.
What's the point of using str_replace() to manipulate the text representation of a date when you know its format? DateTime::createFromFormat() can be used to parse the string into a DateTime object.
There is no need to compute the difference of the two dates and the format it and compare the value to 0. The DateTime objects can be compared directly.
All in all, all the code you need is:
// Current date & time
$today = new DateTime();
// Ignore the time (change $today to "today at midnight")
$today->setTime(0, 0, 0);
// Parse the value retrieved from the database
$field = DateTime::createFromFormat('d/m/Y', $field_value);
// We don't care about the time components of $field either (because the time
// is not provided in the input string it is created using the current time)
$field->setTime(0, 0, 0);
// Directly compare the DateTime objects to see which date is before the other
if ($field < $today) {
echo "1";
} else {
echo "2";
}

converting H:i:s to minutes only but array_map() giving errors

I am trying to convert a long datatype data to time in which I am successful.
In each session time array I have values like ["1276999","787878","677267"]. I passed this array in the array_map function and converted to time which is working.
Now within the the convert_time function I am calling another function, using array_map which will convert each time (i.e 1:40:00 to 100 minutes) but the issue is my 2nd array map function which is giving me error that array_map needs 2nd parameter to be an array...
$each_session_time = array();
for ($i=0; $i<sizeof($array_in_time_str) ; $i++) {
$each_session_time[$i]=$array_out_time_str[$i]-$array_in_time_str[$i];
}
//session time in hours
array_map("convert_to_time", $each_session_time);
function convert_to_time($each_session) {
# code...
$each_sess_time=array();
$each_sess_time=date("H:i:s",$each_session);
array_map("get_minutes",$each_sess_time);
return $each_sess_time;
}
function get_minutes($session_time) {
// algorithm to convert each session time to minutes)
}
You need to move out the array_map("get_minutes",$each_session_time); from the convert_to_time function.
example:
<?php
$each_session_time=["1276999","787878","677267"];
//session time in hours
$times = array_map("convert_to_time", $each_session_time);
$minutes = array_map("get_minutes",$times);
function convert_to_time($each_session)
{
# code...
$each_sess_time=array();
$each_sess_time=date("H:i:s",$each_session);
return $each_sess_time;
}
function get_minutes($session_time)
{
//algo to convert each session time to minutes)
}
print_r($minutes);
It seems you are starting with valid timestamps - seconds passed since January 1, 1970 - so to get the difference between two values in minutes, you just have to subtract one from the other and multiply it by 60.
If you want more control over your data, for example to format it differently later on, I would recommend using DateInterval objects instead of the difference between two timestamps and strings that you are using now. Note that the difference between two timestamps is not a valid timestamp itself so you cannot use date() to format it.
considering you are working with strings like "XX:YY:ZZ" you can try
$split = explode(":",$session_time); $minutes = $split[1];
to get the "i" part of the string.
You could also use a dateTime object (http://php.net/manual/en/class.datetime.php) by doing new DateTime($each_session); in the first loop and using DateTime::format("H:i:s") and DateTime::format("i") on that object depending on what data you need

PHP membervariables DateObject modify

In this code
$start = $this->getStart();
var_dump($start);
$start->modify('Monday this week');
var_dump($this->getStart());
-
public function getStart()
{
return $this->start;
}
how is it possible, that the second dump actually shows the modified date?
I know that modify operates on the date object itself and not merely returns the new value. But why is the actual object property changed? When I change the value otherwise, e.g.
$start = $this->getStart();
var_dump($start);
$start = false;
var_dump($this->getStart());
two times the same date is dumped, as I would expect.

Categories