Laravel Importing CSV throws error on rows with dates - laravel

Import.php
...
return new Statement([
'account_number' => $row['accountno'],
'account_name' => $row['name'],
'reading_date' => \Carbon\Carbon::createFromFormat('m/d/Y', $row['billdate']),
'due_date' => \Carbon\Carbon::createFromFormat('m/d/Y', $row['duedate']),
]);
...
Error:
Illuminate\Database\QueryException PHP 8.1.6 9.37.0
SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '10/18/2022' for column `mubsdb`.`statements`.`due_date` at row 1
INSERT INTO
`statements` (`due_date`, `reading_date`)
VALUES
( 10 / 18 / 2022, 10 / 03 / 2022),
(
10 / 18 / 2022,
10 / 03 / 2022
),
( 10 / 18 / 2022, 10 / 03 / 2022),
( 10 / 18 / 2022, 10 / 03 / 2022),
(10/18/2022, 10/03/2022), (10/18/2022, 10/03/2022), (10/18/2022, 10/03/2022),
DB Structure:
Name Type Null Default
reading_date date Yes NULL
due_date date Yes NULL
I'm trying to import and save csv rows to my DB but I get error with dates. I tried \Carbon\Carbon::createFromFormat('m/d/Y', $row['billdate']) and \Carbon\Carbon::parse($row['billdate'])->format('Y-m-d') but neither seems to work

weirdly, this worked.
'reading_date' => $row['billdate'] ? \Carbon\Carbon::createFromFormat('m/d/Y', $row['billdate'])->format('m/d/Y') : null,
'due_date' => $row['duedate'] ? \Carbon\Carbon::createFromFormat('m/d/Y', $row['duedate'])->format('m/d/Y') : null,

If you're using the newest version of laravel-excel, then you'll notice at this page a date column is exported using Date::dateTimeToExcel:
// ...
Date::dateTimeToExcel($invoice->created_at),
// ...
That is because date is stored as numbers in excel, thus a datetime object needs to be converted first in order to show the value correctly.
This rule also exists in import. So personally I would add a rule in the import class to make sure that the date we're receiving is a number (which actually a date format in excel):
use Maatwebsite\Excel\Concerns\WithValidation;
class MyImport implements WithValidation
{
public function rules(): array
{
return [
'created_at' => ['numeric'],
];
}
}
And then, when about to importing the data using model, convert the number to datetime before modifying it with Carbon:
use PhpOffice\PhpSpreadsheet\Shared\Date;
// ...
return new Import([
// ...
'created_at' => Carbon::instance(Date::excelToDateTimeObject($row['created_at'])),
// or any other Carbon methods
// ...
]);

Related

Compare one date value with other dates and perform conditional action in cypress

I'm trying to compare one date value (ie. base value) with all other date values on a page and based on the difference between these days, I want to execute other commands.
Well, in the above UI, the base value is 11 Jul 2021 (Departure date in the first list) and other date values are 12 Jul 2021, 20 Jul 2021, 27 Jul 2021, 3 Aug 2021 and so on (Arrival dates from 2nd list onwards).
Now, I had to delete the all list(s) where the date difference between the base value and particular list is less than 15 days.
In this case, 12 Jul 2021, 20 Jul 2021 had to be deleted and all lists from 27 Jul 2021, 3 Aug 2021 and so on should be untouched as in the below picture.
So far, I have captured the value of the base value and came up with logic to compare it with another date value but I am not sure how I can save the 2nd and further date value(s) to a variable in order to compare with the base value.
{
cy.get("[data-test='departureTime']")
.eq(0)
.then((date) => {
const depDate_FirstPort = new Date(date.text());
cy.log(depDate_FirstPort.toISOString()); //2021-07-11T19:00:00.000Z
// const arrDate_SecondPort = new Date(cy.get('[data-test="arrivalTime"]').eq(1).invoke('text'));
// Since the above approach does not work, hard coding now.
const arrDate_SecondPort = new Date("22 Jul 2021 12:01")
cy.log(arrDate_SecondPort.toISOString()); //2021-07-22T10:01:00.000Z
cy.getDifferenceBetweenDates(depDate_FirstPort,arrDate_SecondPort).then((dif)=>{
if(dif < 16) {
cy.log("delete the port entry");
//do something
}
});
});
}
Cypress Command:
Cypress.Commands.add("getDifferenceBetweenDates", (Date1, Date2) => {
var diff_times = Math.abs(Date1.getTime() - Date2.getTime());
var diff_days = Math.ceil(diff_times / (1000 * 3600 * 24));
cy.log(diff_days) //11
})
Also, curious to know a possible approach to iterate all list falls under the 'to be deleted list' (12 Jul 2021, 20 Jul 2021) based on the condition mentioned above.
The iterative approach you have is ok, but you need to repeat the code you have for the first date to get the subsequent dates.
So, this bit but changing the index
cy.get("[data-test='departureTime']")
.eq(0) // 1,2,3 etc
.then((date) => {
A different approach is to filter the whole set,
const dayjs = require('dayjs') // replaces Cypress.moment
// first install with
// yarn add -D dayjs
it('finds the skipped ports', () => {
// helper func with format specific to this website
const toDate = (el) => dayjs(el.innerText, 'D MMM YYYY HH:mm')
cy.get("[data-test='departureTime']")
.then($departures => {
const departures = [...$departures] // convert jQuery object to an array
const first = toDate(departures[0]);
const cutoff = first.add(15, 'day')
const nextPorts = departures.slice(1) // all but the first
const skipPorts = nextPorts.filter(port => toDate(port).isBefore(cutoff))
expect(skipPorts.length).to.eq(2)
expect(skipPorts[0].innerText).to.eq('12 Jul 2021 14:02')
expect(skipPorts[1].innerText).to.eq('21 Jul 2021 04:00')
})
})
I'm not clear about your goal, but if you are going to actually delete the skipPorts from the page instead of just testing them, you should be wary of the DOM list changing as you do so.
Deleting from the list you have recently queried with cy.get("[data-test='departureTime']") would cause the internal subject to become invalid, and you might get "detached from DOM" errors or delete the wrong item.

Laravel add 30 minutes to created_add for expired

and I want to show all data in table Transaction using Laravel I'm using index.blade.php into Table
so, when someone makes a transaction, I give them 30 mins. example startTime= 2020-04-26 21:04:00endTime should be= 2020-04-26 21:34:00
so when current time= 2020-04-26 21:24:00, that row will change to yellow
whencurrent time= 2020-04-26 21:32:00````, that row will change to red
What should I do?
this is my index
this is my transaction.php
this is my transactionController#index
this is my transactionControlelr#store
this is my create table transaction
If you want to add 30 min to some time just do this:
[
startTime => date('Y-m-d H:i:s'),
endTime => date('Y-m-d H:i:s', strtotime('+30 minutes'))
]
If you need to add 30min to some specific datetime, then use this:
$specificDateTime = '2020-04-26 21:32:00';
$increased = date('Y-m-d H:i:s', strtotime($created_at . '+30 minutes'));

Logstash ignoring multiple date filters

i'm making a logstash .conf, and on my filter i need to extract the weekday of two timestamps, but Logstash act as if he only is making one match, example:
Timestamp 1: Mar 7, 2019 # 23:41:40.476 . => Thursday
Timestamp 2: Mar 1, 2019 # 15:22:47.209 . => Thu
Expected Output
Timestamp 1: Mar 7, 2019 # 23:41:40.476 . => Thursday
Timestamp 2: Mar 1, 2019 # 15:22:47.209 . => Fri
These are my filters:
date {
match => ["[system][process][cpu][start_time]", "dd-MM-YYYY HH:mm:ss", "ISO8601"]
target => "[system][process][cpu][start_time]"
add_field => {"[Weekday]" => "%{+EEEEE}"}
}
date {
match => ["[FechaPrimero]", "dd-MM-YYYY HH:mm:ss", "ISO8601"]
target => "[FechaPrimero]"
add_field => {"[WeekdayFirtsDay]" => "%{+EE}"}
}
It's because by default %{+EEEEE} and %{+EE} take into account the #timestamp field, and no a user made field (don't know it is written in the doc)
The only way of doing that, as far as I know, is using a part of ruby code, to extract day of week, as following :
ruby {
code => 'event.set("Weekday", Time.parse(event.get("[system][process][cpu][start_time]").to_s).strftime("%A"))'
}
ruby {
code => 'event.set("FechaPrimero", Time.parse(event.get("FechaPrimero").to_s).strftime("%a"))'
}

How to format digits in logstash?

How can I format digit in logstash?
I am using the '' % format expression in ruby code in filter plugin but I get nil as format result. I tried sprintf and format function but same result.
Below is my code snippet.
ruby {
code => "
event.set( 'positioning', event.get('branch_lat') + ',' + event.get('branch_lon') )
event.set( 'report_datetime', event.get('report_date') + '%04d' % event.get('report_time') )
"
}
As a format result, I get below error in the log.
[2016-10-28T12:31:43,217][ERROR][logstash.filters.ruby ] Ruby exception occurred: undefined method `+' for nil:NilClass
My platform information is below.
[root#elk-analytic logstash]# rpm -qi logstash
Name : logstash
Epoch : 1
Version : 5.0.0
Release : 1
Architecture: noarch
Install Date: Thu 27 Oct 2016 01:26:03 PM JST
Group : default
Size : 198320729
License : ASL 2.0
Signature : RSA/SHA512, Wed 26 Oct 2016 01:57:59 PM JST, Key ID d27d666cd88e42b4
Source RPM : logstash-5.0.0-1.src.rpm
Build Date : Wed 26 Oct 2016 01:10:26 PM JST
Build Host : packer-virtualbox-iso-1474648640
Relocations : /
Packager : <vagrant#packer-virtualbox-iso-1474648640>
Vendor : Elasticsearch
URL : http://www.elasticsearch.org/overview/logstash/
Summary : An extensible logging pipeline
Description :
An extensible logging pipeline
Added on 2016.10.28 14:32
My Goal is to parse below csv columns into timestamp field in elasticsearch.
Please notice that hour of time has mixed patterns of 1 and 2 digits.
date,time
20160204,1000
20160204,935
I tried using date function in filter plugin but it did not work properly by logging error.
[2016-10-28T11:00:10,233][WARN ][logstash.filters.date ] Failed parsing date from field {:field=>"report_datetime",
:value=>"20160204 935", :exception=>"Cannot parse \"20160204 935\": Value 93 for hourOfDay must be in the range [0,23]", :config_parsers=>"YYYYMMdd Hmm", :config_locale=>"default=en_US"}
Below is the code snippet when above error appeared.
ruby {
code => "
event.set( 'positioning', event.get('branch_lat') + ',' + event.get('branch_lon') )
event.set( 'report_datetime', event.get('report_date') + ' ' + event.get('report_time') )
"
}
# Set the #timestamp according to report_date and time
date {
"match" => ["report_datetime", "YYYYMMdd Hmm"]
}
I did some modification and ended up with the code I first posted.
I suggest to do it like this without any ruby filter:
filter {
# your other filters...
# if 3-digit hours, pad the time with one zero
if [time] =~ /^\d{3}$/ {
mutate {
add_field => { "report_datetime" => "%{date} 0%{time}" }
}
# otherwise just concat the fields
} else {
mutate {
add_field => { "report_datetime" => "%{date} %{time}" }
}
}
# match date and time
date {
"match" => ["report_datetime", "yyyyMMdd HHmm"]
"target" => "report_datetime"
}
}

Laravel 5 and Carbon discrepancy on Forge

Hopefully I'm not mad and I'm only missing something. I have a project on Laravel 5.0 and I have a requestExpired function called every time I have an incoming request. Now, to calculate the difference between current time on the server and the timestamp within the request I'm using:
$now = Carbon::now('UTC');
$postedTime = Carbon::createFromTimestamp($timestamp, 'UTC');
For some reason request is always rejected because it's expired. When I debug these two lines from above and just dump data, I get:
REQUEST'S TIMESTAMP IS: 1423830908279
$NOW OBJECT: Carbon\Carbon Object
(
[date] => 2015-02-13 12:35:08.000000
[timezone_type] => 3
[timezone] => UTC
)
$POSTEDTIME OBJECT: Carbon\Carbon Object
(
[date] => 47089-05-28 09:37:59.000000
[timezone_type] => 3
[timezone] => UTC
)
Any ideas why $postedTime is so wrong? Thanks!
To answer my own question: for some strange reason webhook calls from remote API have 13 digits long timestamps and that's why my dates were so wrong.

Resources