I'm trying to extract the year of a input date like
$start = $request->input('start');
$refYear = DateTime::createFromFormat("Y-m-d H:i:s", $start)->format("Y");
But I'm having the error Call to a member function format() on boolean and i saw another answers but nothing result so far.
Where start is defined as a input in my page
<input id="start" type="text" name="start" class="date-type"
placeholder="dd-mm-aaaa"><i class="fi-calendar" style="top: 2px;"></i>
In my table the startDate column is a date time like '2017-10-26 00:00:00.000' and refyear is a int (2017).
According to the documentation DateTime::createFromFormat:
Returns a new DateTime instance or FALSE on failure.
This is why you call it on a boolean, because the value is false.
Your format seems to be correct, that means createFromFormat can not handle your $start . Your input does not match your format, make sure it matches.
The following for instance works:
echo (DateTime::createFromFormat("Y-m-d H:i:s", "2019-01-01 12:30:30"))->format("Y"); // result: 2019
#jeprubio from the comments is right btw. - add the milliseconds to match your given format:
echo DateTime::createFromFormat("Y-m-d H:i:s.u", "2017-10-26 00:00:00.000")->format("Y"); // 2017
You can try to use Carbon instead:
$refYear = Carbon::createFromFormat("Y-m-d H:i:s", $start)->format("Y");
But also your format is wrong you are missing .u based on your example of the date field. You should use this:
$refYear = Carbon::createFromFormat("Y-m-d H:i:s.u", $start)->format("Y");
Related
I'm trying to convert a string that enters in my program from a JSON to a date, so I can compare it to actual time.
I'm using strtotime() but it converts the original date to 01/01/1970 12:00:00.
Here's my code:
var_dump($requestOrder->date);
$requestDate= date('d/m/Y h:i:s', strtotime($requestOrder->date));
var_dump($requestDate);
Where, date inside the $requestOrder is equal to "24/12/2021 00:00:00".
And here's what I'm getting:
string(19) "24/12/2021 00:00:00"
string(19) "01/01/1970 12:00:00"
I need to convert it to a date because, lately, in some point of my code, I do this:
if($requestDate< date('d/m/Y h:i:s', time())) {
...
}
I've been trying a lot of options to solve this problem, such as changing the / to -, using other formats for the date, etc, but with no luck. In the case of using a str_replace to change the / to -, it works and doesn't show a 70's date, but then it doesn't do the comparison well, it always detects the date smallest to actual one.
Does someone see what I'm skipping?
The date() function returns a string not a DateTime object. It would be better to use the actual DateTime class and its createFromFormat function.
$requestDate = date_create_from_format('d/m/Y h:i:s', $requestOrder->date);
or object oriented style
$requestDate = DateTime::createFromFormat('d/m/Y h:i:s', $requestOrder->date);
https://www.php.net/manual/en/datetime.createfromformat.php
Please check below code:
$requestOrder->date="24/12/2021 00:00:00";
$date=str_replace("/",'-',$requestOrder->date);
if(strtotime($date)>time())
{
//this will execute as request date is greater than current date
}
if(strtotime($date)<time())
{
//this will not execute as current date less than request date
}
I have the code below to add days to a date.
$date = '[[lbc_dates_lbc_date]]';
$date = date('d F y', strtotime('+28 days', strtotime($date)));
echo $date;
This works perfectly for cases where a date entry actually exists, however, it's displaying an odd date for cases where date entry doesn't exist yet (blank).
Can you amend the code to say if a date exists add days, otherwise leave blank?
Please see image attached (errors in red, correct view in green)
Thanks
strtotime() will return FALSE when it can't parse the date. This is being treated as 0, the epoch time, when you use it as the base time in the second call to strtotime().
Check for that before trying to use the result.
$parsed = strtotime($date);
if ($parsed) {
$date = date('d F y', strtotime('+28 days', $parsed));
} else {
$date = '';
}
You should use DateTime object for storing and manipulating dates.
echo $date !== null ? (new DateTime($date))->add(new DateInterval('P28D'))->format('Your date format here') : '';
https://www.php.net/manual/en/class.datetime.php
Basically it uses a ternary operator to check if $date is null, if it's not, it creates a new DateTime object for the current date, adds 28 days and echoes it in a chosen format. If $date is null, it will just echo an empty string - ''.
Edit: The above is just an one-liner example, a good practice would be getting it into a function.
I am trying to take a credit card expiry date in the format of mm-yy and see if that date has passed so I know if the credit card has expired. If it has expired, a class of expired is inserted on the <tr>
My code results in a sample date of 05/16 being checked, and the script says that the card has not expired when obviously this card is a year old.
<?php foreach($card_historys as $card_history){
$expired = "";
$date = strtotime($card_history->expire); //Returns a date in mm/yy
$noww = strtotime(date('m/y'));
echo "expire: ".$date." / now: ".$noww."<br>";
if($date < $noww){$expired = 'expired';}
?>
<tr class="<?php echo $expired; ?>">
What did I do wrong?
When using PHP's built in date functionality, you need to make sure you are using a valid datetime format. Otherwise strtotime() will return false and DateTime() will throw an exception.
To work with non-standard datetime formats you can use DateTime::createFromFormat() to parse the datetime string and return a DateTime() object from which you can get a Unix Timestamp, convert the date into another format, or use it to compare to other DateTime objects.
// Date separated by dots
$date01 = \DateTime::createFromFormat('Y.m.d', '2017.04.18');
// Date with no separator
$date02 = \DateTime::createFromFormat('Ymd', '20170418');
// Get Unix timestamp
$timestamp = $date01->getTimestamp();
// Get MySQL format (ISO-8601)
$mysqlDate = $date02->format('Y-m-d');
So for your issue, you would do the following:
$expires = \DateTime::createFromFormat('m/y', $card_history->expire);
$today = new \DateTime();
if($expires < $today){$expired = 'expired';}
See also:
Convert one date format into another in PHP
Compare DateTime objects with comparison operators in PHP
I am using DateTime function of php. I get a date from a calendar in format d-m-Y and pass it via ajax to my function. I am getting the date right till this step.
When I try to store the date in unix format using:
$ai_ff_date=DateTime::CreateFromFormat('d-m-Y', $data['date']);
$final_date=$ai_ff_date->format('U');
The date stored is wrong. Suppose the date I passed via ajax is 26-12-2016 then in database 27-12-2016 is stored. Why its counting one more day then the input.
use this code :
$date = date('Y-m-d H:i:s', strtotime('-1 day', $stop_date));
$ai_ff_date=DateTime::CreateFromFormat('d-m-Y',$date);
$final_date=$ai_ff_date->format('U');
and please check the variable (code not tested)
You might want to convert the Date-Format to "Y-m-d" First and then call-in the DateTime() Constructor. However, since what you are trying to do is just get the TimeStamp you might also do that directly without using DateTime. The Snippet below shows what is meant here:
<?php
$data = ['date'=>"13-12-2016"]; //<== JUST AN EXAMPLE FOR TESTING!!!
// SIMPLY CONVERT THE DATE TO Y-m-d FIRST.
$dateYMD = date("Y-m-d", strtotime($data['date']));
// THEN USE DateTime CONSTRUCTOR TO CREATE A NEW DateTime INSTANCE
// AND THEN RUN THE FORMAT YOU WISH::
$final_date = (new DateTime($dateYMD))->format('U');
var_dump($final_date); //<== YIELDS: string '1481583600' (length=10)
var_dump(date("Y-m-d", $final_date)); //<== YIELDS: string '2016-12-13' (length=10)
An iCalender file expects the DTSTART and DTEND parameters in its file to be of the format:
20140715T035959Z
Basically, long form year, double digit month, double digit day, the letter 'T' to break the date from the time, then double digit hour, minute, second, etc. appended with the letter 'Z'.
I currently have a date in the following PHP format:
Y-m-d H:i:s
I'm currently trying to format it with the DateTime::format method into an iCalender accepted string, and I thought this might work:
format('Ymd\THis\Z');
I've escaped the characters T and Z in the hopes they would appear, but when my event is echoed into the file, it's simply empty. I have a feeling my representation of the iCal datetime format is incorrect. Ideas?
Current iCal code:
DTSTART:".$calData->eventStart()."
Current $calData->eventStart() code:
public function eventStart() {
$inputDateTime = $this->details['date_time'];
// Convert MySQL datetime to ical datetime
$temp = DateTime::createFromFormat('Y-m-d H:i:s', $inputDateTime);
$eventStart = $temp->format('Ymd\THis\Z');
echo $eventStart; // This should be RETURN, not ECHO!
}
ANSWER:
Yeah, so it turns out this was a non-question. I was simply echoing the datetime instead of returning it.
You could try something like this...
<?php
$pubDt='20140715T035959Z';
$pubDt=str_replace(array('T','Z'),array('',''),$pubDt);
$format = 'Ymdhis';
$date = DateTime::createFromFormat($format, $pubDt);
echo $newPubdate = $date->format('Y-m-d H:i:s'); //"prints" 2014-07-15 03:59:59