how to compare two dates in if condation in laravel blade? - php

in my controller i used Carbon to get current timestamp like showing below:
$current_timestamp = Carbon::now()->format('j/n/Y');
the output of the above:
18/8/2022
and i am getting data from external API like showing below (from blade):
$data[0]['DocDate']
the output of the above:
18/8/2022 12:00:00 AM
now i want to remove 12:00:00 AM from it
i tried in blade view to do:
{{Carbon\Carbon::parse($data[29]['DocDate'])->toDateString()}}
but i am getting this error:
Could not parse '18/8/2022 12:00:00 AM': Failed to parse time string (18/8/2022 12:00:00 AM) at position 0 (1): Unexpected character
and i tried:
$data[29]['DocDate']->format('j/n/Y')
and i get this error:
Call to a member function format() on string
how can i overcome this issue?

You can use create from format function to change the format of incoming date as below:
$inDate = $data[0]['DocDate'];
$outDate = Carbon::createFromFormat('d/m/Y h:i:s a', $inDate )->format('d/m/Y');

On the principle of Keep It Simple - Why not just compare them as strings?, the longer one can easily be shortened, then just compare.
Accepted this is not a "purest" approach, but the format of a "standard" date is not likely to change.

now i want to remove 12:00:00 AM from it
So you don't actually care about date, you don't need Carbon or parsing according to format, you just need to keep the first word of your string:
{{ explode(' ', $data[0]['DocDate'])[0] }}

Related

The separation symbol could not be found Data missing

I'm working with Laravel 5.8 and I wanted to show a popup message if the UNIX timestamp of the current date is equal to the defined Unix timestamp of the popup.
So in order to do that, I added this at the Controller:
$date1= $popup->datep; // returns 1636403400
$date1 = Carbon::createFromFormat('Y-m-d H:i:s', $date1);
dd($date1);
But instead of getting the result of $date1, I get this error:
The separation symbol could not be found Data missing
So what's going wrong here? How can I solve this issue?
You are specifying a format that is clearly not an unix timestamp. Use method for the timestamp.
$date = Carbon::createFromTimestamp($popup->datep);
If you want to compare it to be the same date, you should do the following. I don't assume you want to compare it by the hour or second, that those will almost never match.
$date->startOfDay()->eq(now()->startOfDay());
Regarding Carbon Docs:
createFromFormat() is mostly a wrapper for the base php function DateTime::createFromFormat.
which is means that your second parameter must be a valid date/time format, not a timestamp.
The DateTime::create docs:
$datetime
String representing the time.
Instead, you need to use the createFromTimestamp instantiator.
$date1 = Carbon::createFromTimestamp($date1);

Laravel - format date to store it on MySQL database

I am using Laravel and I have to get some dates and store it on MySQL database.
When I create the date like this:
$date_sol = Carbon::createFromFormat("Y-m-d H:i:s","2020-12-10 01:00:00");
The date is properly stored on the database. However, I have to get the date from an input.
I am trying to get the date and then format it like this:
$novaData = $request->input('solicitacao_data') . ' 15:16:17';
$sol->data = Carbon::parse($novaData)->format("Y-m-d H:i:s");
However, I get the error:
DateTime::__construct(): Failed to parse time string (28/03/2020
15:16:17) at position 0 (2): Unexpected character
The error is at the line $sol->data = Carbon::parse($novaData)->format("Y-m-d H:i:s");
How do I make the formating conversion properly? I am new using Laravel. I am not sure about it.
For date format 'd/m/Y' try this.
Carbon::createFromFormat('d/m/Y', '22/02/2020')->toDateTimeString();
Similarly for date format Y-m-d try this
Carbon::createFromFormat('Y-m-d', '2020-02-22')->toDateTimeString();
output will be in format (Y-m-d H:i:s)
"2020-02-22 21:05:13"
Let's say you receive something as input.
Well, ideally you should first sanitize it, to make sure you received a string that can be interpreted as a date. For that, I would suggest you to have a look there :
php date validation
So, you assign the input to a var and append a string representing some time to it:
$novaData = $request->input('solicitacao_data'). ' 15:16:17';
From here, the easiest is to convert the string into a timestamp. Which can be achieved this way:
$time = strtotime($novaData);
And now, you can use Carbon to format the date the way you want :
$sol->data = Carbon::createFromTimestamp($time)->format("Y-m-d H:i:s");

Fatal error: Call to a member function format() on boolean passing in Wordpress ACF Datepicker to template

Here is my code:
$original_date = get_field('event_date');
$date = DateTime::createFromFormat('lFdY', strtotime($original_date));
$new_date = $date->format('l, F d, Y');
This code is in a custom post loop in a shortcode and called in the Wordpress admin.
I have also tried it without the strtotime. I am using PHP 5.6.
The event_date field is from an Advance Custom Fields date picker.
If I just pass the field, I get my intended output (the input from the custom post admin page), but without whitespace and commas. I also set this, save and display values in the acf in WP.
This is the error:
Fatal error: Call to a member function format() on boolean on the line
with $new_date variable.
Then if I use:
$date = date("l, F d, Y", strtotime($original_date));
The loop throws an error, undefined variable, for each instance of the post.
You should pass the string directly to the createFromFormat method:
$date = DateTime::createFromFormat('lFdY', $original_date);
The boolean you're receiving is because createFromFormat is failing and returning false.
If you're still receiving an error, get_field() is likely not returning what you think it is.
Try using this .. <?php echo date('l, F d, Y', strtotime(get_field('event_date')));?> it is working at my end
Make sure your get_field('event_date') returns you the date in 20160113 format If not then change the return format from ACF setting in WP back-end.
DateTime::createFromFormat returns false if it fails to convert the input string using the format specified.
In your case, you're taking an $original_date, converting it to a numeric timestamp, and trying to pass that in to DateTime::createFromFormat, which isn't going to work, hence the error. You'll need to pass in the original date instead:
$date = DateTime::createFromFormat('lFdY', $original_date);
PHP currently can not parse that specific format string. You can demonstrate this with an easy case that should "obviously" work. This:
DateTime::createFromFormat('lFdY', date('lFdY', time()));
returns false. The issue is specifically because of the lack of space between l and F in the format string and between the day-of-week and month in your input string.
You should use a different date format. If you can remove the text representation of the day-of-week (because it's not actually necessary to disambiguate the date), or at least get a space between the day-of-week and the month, that would be best.
Since you have existing data in your database in an unhelpful format, you could write a relatively simple pre-processor to remove the day-of-week from the input string:
$new_date = substr($original_date, strpos($original_date, 'y') + 1);
$date = DateTime::createFromFormat('FdY', $new_date);
(This example assumes always english day names, in lowercase, and the input is always valid. You may need more complicated code for your actual data.)
Nitty, gritty details: When PHP processes the l formatter (day of week), it requires seeing one of the characters in: ,;:/.-(), a space, tab, or end-of-string as an indication of where to stop reading.
So, if your date string is FridayJuly082016, because there are no spaces whatsoever in the input date, the code continues reading the entire string, and then fails because (literally) FridayJuly082016 is not in the list of days of the week.
Unfortunately for your particular case, this is also not likely to be "fixed". You have an extremely unusual date format, and making this particular case work in the code would make it considerably more complicated, for a questionable and rare use case.
#jbafford I found a solution.
First I save the date format to yymmdd in the ACF datepicker field
Then I used this code to extract the year month and date separately and then formatted the strtotime result:
$odate = get_field('event_date');
$y = substr($odate, 0, 4); $m = substr($odate, 4, 2); $d = substr($odate, 6, 2);
$new_date = date('l, F j, Y', strtotime("{$d}-{$m}-{$y}"));
What confused me I think and got me hung up was the presumption that I had to pass l or the day into the strtotime and that I had to match input with the intended formatted output. PHP date doesn't need that much info to accomplish the task. Thanks for all of your input!

inject date string as srtotime

I am trying to resolve this since hours, and I tried different solutions offered here within the website, but for some reasons the website always returns an error when applying the suggestions.
I have a form field which uses a datepicker, and the output is a date in the format: November 6th, 2013
Now, the mysql database and the rest of the script only works with a ten digit date format, which I have been told is the unix timestamp format and that it can be converted using the strtotime. So I am trying to convert the string into strtotime, but cant resolve this. For now I have:
$insertData['enddate'] = $this->input->post('openDays');
which returns the date "November 6th, 2013" and I changed it to
$insertData['enddate'] = strtotime $this->input->post('openDays');
which returns the error: Parse error: syntax error, unexpected T_VARIABLE in /home/xxx/public_html/app/controllers/project.php on line 214
any suggestions on how to correctly apply this?
Thanks
Try this, you are doing a mistake by using strtotime.
$insertData['enddate'] = strtotime($this->input->post('openDays'));
Reference link: Strtotime PHP
strtotime is a function , so you need to enclose it like this (using parenthesis)
$insertData['enddate'] = strtotime($this->input->post('openDays'));
-------^ -------^
EDIT :
I suggest you use DateTime instead of strtotime
$dt = DateTime::createFromFormat('H:i', '17:00');
$insertData['enddate']=$dt->format('H:i');

How to format date in PHP from a string of concatenated numbers?

I am new to PHP and I am trying to learn more of php date and time but I seem to get stuck with this.
I have this date format:
ddMMyyHHmmss
And an example is 120813125055 but I am trying to manipulate the string such that it will give me the format of:
yyyy-MM-dd HH:mm:ss (in the example above, 2013-08-12 12:50:55)
I tried to do something like:
date('Y-m-d H:i:s', strtotime('120813125055'));
But it always gives me a result of 1969-12-31 18:00:00.
I assume that I need to do some string manipulation in PHP for this but I was wondering if there is an easier and more efficient way to do it?
I think what you're looking for is in the second response answered here: how to re-format datetime string in php?
To summarize (and apply to your example), you could modify the code like this.
$datetime = "120813125055";
$d = DateTime::createFromFormat("dmyHis", $datetime);
echo $d->format("Y-m-d H:i:s");
Use date_create_from_format:
$ts = date_create_from_format('dmyHis', '120813125055');
$str = date('Y-m-d H:i:s', $ts);
strtotime() only works on EASILY recognizable formats. Your is a ugly mix of garbage, so no surprise that strtotime bails with a boolean FALSE for failure, which then gets typecast to an int 0 when you tried feed it back into date().
And of course, note that your time string is NOT y2k compliant. two digit years should never ever be used anymore, except for display purposes.
You're using your function call and the argument the wrong way around.
In your example, php will try to return you the date for which the time is 'strtotime('120813125055')', and this function returns false (interpreted as 0). So you get returned the date formatted in 'Y-m-d H:i:s' for the Unix epoch.
You will need to get the actual timestamp of your string, so use http://www.php.net/manual/en/datetime.createfromformat.php.
You are mistaken here..
I tried to do something like:
date('Y-m-d H:i:s', strtotime('120813125055'));
You shouldn't use only numbers ( doesnt matter its an integer or a string ), than it will always give you the same thing.
You can use any other valid date and time ( E.G. 6 Jun 2013, 5 may 12...) . Because what strtotime() do is detect a valid date and convert it into timestamp.

Categories