Laravel Eloquent date_format Validation fails on given format - laravel

I want to create validation rule to validate incoming date.
Format I want to validate is Y-m-d H:i:s. Here's my body request which I am validating:
{ "date":"2015.10.5 10:30:10" }
And here's my validation rule:
'date' => 'required|date_format:"Y.m.d H:i:s"',
And it returns:
{"date":["The date does not match the format Y.m.d H:i:s."]}

If you want to be able to pass the day without a leading zero, then for the day part of your datetime you need to use j instead of d.
'date' => 'required|date_format:"Y.m.j H:i:s"',
That will work for the example you have above.
If you are going to always have a leading zero in your day (so, 05 instead of just 5, then the date format you already have will work.

Related

Double time specification in file in laravel api

I am making api's in laravel and getting 2021-01-30T10:30:17.704 05:30 from $request->followup and i have column in database named followup having datetime datatype. But it's giving me following error.
Carbon\Exceptions\InvalidFormatException: Could not parse '2021-01-30T10:30:17.704 05:30': DateTime::__construct(): Failed to parse time string (2021-01-30T10:30:17.704 05:30) at position 24 (0): Double time specification in file D:\xampp2\htdocs\synocrm-baid\rest-apis\vendor\nesbot\carbon\src\Carbon\Traits\Creator.php on line 188
I tried to change format like
$followupDate = date('Y-m-d h:i:s A',strtotime($request->followup));
My modal having
#property Carbon|null $followup
$request->followup is appending datetime with datetime
Original Value: 2021-01-30T10:30:17.704 05:30
Datetime: 2021-01-30T10:30:17.704
Time: 05:30
As we can see, there is two Time (05:30 and 10:30:17), because of which the strtotime() cannot convert the value.
In order to fix the problem,
Send the value as time time only (2021-01-30T10:30:17.704) instead of two times Time attribute
If you have no control over request value, you can retrieve only date value like:
$dateValue = explode(' ', $request->followup)[0];
$followupDate = date('Y-m-d h:i:s A',strtotime($dateValue));
Or Using Carbon
$followupDate = Carbon::parse($dateValue);
I would not recommend option 2 because it creates problems and confusion for other devs.
2021-01-30T10:30:17.704 05:30
It does not seem to valid timestamp. For parsing, it should be the valid timestamp or date.

How to update ends_at field of laravel cashier

I want to update ends_at column of subscriptions table. When i use
Carbon::now()
It update perfectly but when is use
Carbon::now()->addCenturies(5);
I am face error
SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2520-08-07 11:39:13' for column 'ends_at' at row 1 (SQL: update `subscriptions` set `ends_at` = 2520-08-07 11:39:13, `subscriptions`.`updated_at` = 2020-08-07 11:39:13 where `id` = 1)
i want one subscription for life time due to this i think add centuries. kinldy tell me solution my controller code is
$subscription = $user->newSubscription('default', $plan->plan_id)->create($request->paymentMethod, [ 'email' => $user->email ]);
$subscription->ends_at = Carbon::now()->addCenturies(5);
$subscription->save();
The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of 1970-01-01 00:00:01 UTC to 2038-01-19 03:14:07 UTC. Your given year is 2520 and your MySQL can handle year as max 2038.
Change the migration timestamp to dataTime format as :
$table->timestamp('ends_at');
to
$table->dateTime('ends_at');
It looks like ends_at is meant to be managed for you by Laravel Cashier, not something you modify manually. Reviewing the source code, it is only updated based on other values, not any parameters. It also is not used to set any parameters in Stripe API requests. The cancel_at parameter would seem to most likely mapping.
If you wish to set cancel_at, it takes an epoch timestamp (in seconds). As #sta mentioned above, this has a maximum value of 2147483647, representing a time in 2038.
Note also that Subscriptions will by default continue in perpetuity, so it is not necessary to set an "end date" 5 centuries from now.

Using Carbon I got "textual month could not be found" error

In my Laravel 5.8 application, I to convert date in string format like
02 May, 2019 to date time using Carbon. I try like :
setlocale(LC_TIME, 'en');
$filter_check_in_datepicker_till = Carbon::createFromFormat( 'dd MMMM YYY', $filter_check_in_datepicker_till )->locale('en_EN');;
But got error:
"message": "Unexpected data found.\nA textual month could not be found\nData missing",
Which is right way?
Thanks!
The Carbon docs say:
createFromFormat() is mostly a wrapper for the base php function DateTime::createFromFormat.
It isn't entirely clear from the docs, but that means the $format parameter passed to createFromFormat() is a DateTime format, not a Carbon format. So instead of dd MMMM YYY, you should use d, M Y (check the DateTime format reference):
\Carbon\Carbon::createFromFormat('d, M Y', '02, May 2019');
// returns 2019-05-02 12:48:26
For reference, there are several problems in your Carbon format, so even if createFromFormat took a Carbon format string what you have would not work. Checking the Carbon format reference:
dd is actually "Minified day name (from Su to Sa), transatable". You really want DD for the zero-padded day of month;
The date format you are using includes a comma, but your format string is missing that;
YYY is not actually a valid Carbon format string. You really wanted YYYY for 4-digit year;

How to convert dates within an array to a specific format

I have an array of dates, where the dates have different formats. I would like to convert them all to the same format, however what I've tried has caused me some problems.
I get the dates from a SQL query:
table_birth_dates = self.class.connection("SELECT birth_date FROM #{temp_table_name}").values
which gives me an array of dates:
[
[0] "10/3/80",
[1] "10/3/81",
[2] "10/3/01",
[3] "33/33/1970",
]
I want to get the year as a full year like above.
I tried:
table_birth_dates.first.to_time
and got:
ArgumentError: argument out of range
I also tried:
Date.strptime(table_birth_dates)
and got:
no implicit conversion of Array into String
Does anyone have any ideas?
As the others already said: Don't store arbitrary strings as date! Use your database and store dates as date or datetime. See documentation of your database. (See comment from #the-tin-man.)
That said you can try the following with your current date:
table.map! { |date|
date_hash = Date._strptime(date, '%m/%d/%Y') # {:mon=>10, :mday=>3, :year=>70}
if date_hash.nil?
'invalid'
else
date_hash[:year] = date_hash[:year] + 1900 if date_hash[:year] < 1000
Date.new(date_hash[:year], date_hash[:mon], date_hash[:mday])
end
}
This gives you an array with actual dates like so:
[
1980-10-03
1981-10-03
1901-10-03
invalid
]
Of course you should do something about this invalid but it serves your main purpose.
If all you dates is on the the same format as the first 3 dates you can use this con change the format of the dates:
dates.map! do |date|
Date.strptime(date, '%d/%m/%y').strftime('%d/%m/%Y')
end
If you have dates on different formats you could list the formats you have and try to parse each of them and see if you get a valid result, however dates like 33/33/1970 is not a valid date at all.
Parsing dates isn't as straightforward as people assume when they first start working with them, because dates are represented differently around the world.
'10/3/80'
would represent "October 3, 1980" in a U.S. formatted date, but would be "March 10, 1980" in the rest of the world. And, the software has no idea which it is unless you tell it which to use. And, if your data comes from around the world you can't tell unless you know what locale the data was generated in or unless they explicitly tell you what format it's in.
require 'date'
Date.strptime('10/3/80', '%m/%d/%y') # => #<Date: 1980-10-03 ((2444516j,0s,0n),+0s,2299161j)>
Date.strptime('10/3/80', '%d/%m/%y') # => #<Date: 1980-03-10 ((2444309j,0s,0n),+0s,2299161j)>
From DB, bring date in integer format and convert back to any specific format.
Are you storing date in DB as string and trying to convert them for unique format to display? If so, you can correct while storing the value (or) add a column in DB which gets updated whenever your date column gets inserted/updated and retrieve from new column.

Input mask with only past dates validation

I am using Input mask from this link. My input mask working correctly. But i want validation for past dates only from current date. But i don't get any condition for this.
You can use below yearrange hash for setting up the past date validation.
$("#date_of_birth").inputmask("mm/dd/yyyy", { yearrange: { minyear: 1900, maxyear: 2015, }});

Resources