Laravel - Carbon ->addmonth() giving random dates? - php

We're having problems creating a webhook service for a payment using "Mollie".
Here's the webhook code
public function premiumPaymentCheck(Request $request)
{
$payment = Mollie::api()->payments()->get(Input::get('id'));
$metadata = $payment->metadata;
$user_id = $metadata->user_id;
if ($payment->isPaid()) {
$user = User::find($user_id);
$user->mollie_customerID = $metadata->customerId;
$user->premium = true;
$user->premium_type = "premium";
$user->subscribed = true;
$user->premium_expire_date = Carbon::now()->addMonth();
$user->save();
}
}
Everything works, except for the premium_expire_date. From what I understand, it should add 1 month from the payment time (the time the payment calls the webhook, so Carbon::now()), but the dates never match.It's always a random date that doesn't really make sense.
Some of the dates are correct, but most of them seem completely of. Any Idea what this might be?

There is no problem with carbon. Check your config/app.php file for timezone property.
'timezone' => env('APP_TIMEZONE', 'UTC'),

Timezone is currently:
'timezone' => 'UTC',
We are in Belgium/Brussels. So should it be:
'timezone' => env('Europe/Brussels', 'UTC')
Alternately it could be:
'timezone' => 'Europe/Brussels',
Thanks for the help!

Related

Insert the current date time using Laravel

I want to store the current date time in MySQL using the following Laravel function. Actually, I stored a static date. Instead of this, how can I store the current date time in the created_at and updated_at fields in the database?
function insert(Request $req)
{
$name = $req->input('name');
$address = $req->input('address');
$data = array("name" => $name, "address" => $address, "created_at" => '2017-04-27 10:29:59', "updated_at" => '2017-04-27 10:29:59');
DB::table('student')->insert($data);
echo "Record inserted successfully.<br/>";
return redirect('/');
}
Use the Laravel helper function
now()
Otherwise, use the carbon class:
Carbon\Carbon::now()
It is used like this:
$data = array("name" => $name,"address" => $address,"created_at"=> Carbon::now(),"updated_at"=> now());
DB::table('student')->insert($data);
For more information, see now()
You can also use this to get the current date time. It's working.
$current_date = date('Y-m-d H:i:s');
And also I have updated and set things in your function. You have to add this:
function insert(Request $req)
{
$name = $req->input('name');
$address = $req->input('address');
$current_date_time = date('Y-m-d H:i:s');
$data = array("name" => $name,
"address" => $address,
"created_at" => $current_date_time,
"updated_at" => $current_date_time);
DB::table('student')->insert($data);
echo "Record inserted successfully.<br/>";
return redirect('/');
}
Use this in your database query:
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
You can use the DateTime object.
Look at the below code:
$curTime = new \DateTime();
$created_at = $curTime->format("Y-m-d H:i:s");
$updateTime = new \DateTime();
$updated_at = $updateTime->format("Y-m-d H:i:s");
Use
use Carbon\Carbon;
at the header of the controller. This code work for Laravel 9:
$updated = Carbon::now();
You may save it inside a variable and use the variable for inserting and updating statements or for any other purpose.
During migration, I defined the column check_at as datetime. And I used the following command for table creation.
php artisan migrate
It generates a timestamp-type column in MySQL. I am passing the variable $updated for update purposes. While using phpMyAdmin, I can see the column check_at has data in date-time format.

Trouble with date and time formats saving in my database

I have trouble saving my date and time values. I tried different formats, here the actual try.
validator in my form:
$datum=$this->CreateElement('text','datum')
->setAttrib('size', '10')
->addValidator(New Zend_Validate_Date('MM-DD-YYYY'));
$zeit=$this->CreateElement('text','zeit')
->setAttrib('size', '10')
->addValidator(new Zend_Validate_Date(array('format' => 'H:i:s')));
Snippet of my Controller addAction
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$logenr = $this->_getParam('kopfnr', 0);
$kopfnr = $logenr;
$dat= $form->getValue('datum');
$zeit = $form->getValue('zeit');
$thema = $form->getValue('thema');
$aktermine = new Application_Model_DbTable_Aktermine();
$aktermine->addTermine( $kopfnr, $dat, $zeit, $thema);
And, my add function in my database class:
public function addTermine($kopfnr, $datum, $zeit, $thema)
{
$data = array(
'kopfnr' => $kopfnr,
'datum' => $datum,
'zeit' => $zeit,
'thema' => $thema,
);
$this->insert($data);
}
I´m using a mySQL database on a WAMP installation.
Where is my error? As a remark I want to say, I get a new record, the value of "thema" and the keys are properly saved, so I think it must be some format thing somewhere.
EDIT: I get a new record but the fields date and time are empty. I get no errors
NEW: I added a debug test in my controller to see what comes for the date value, here is the answer:
string '01-04-2016' (length=10)
(I put in 01-04-2016)
By reading your comments I understand you have two problems. The first one is putting the date into your table and the second is to let the user use the normal date format (dd/mm/yyyy).
First problem is solved when you reformat the user input before putting it into the database.You can add the following line into the $form->isValid($formData) part:
$dat = (new DateTime($form->getValue('datum')))->format('Y-m-d');
This oneliner will convert the date from 'dd-mm-yyyy' to 'yyyy-mm-dd'.
thanks, after the suggestion to debug I changed the format of my date like this: $test1=date('Y/m/d',strtotime($dat));
And now it works!

Magento and BST Timezone issue

I running a Magento store in CentOS on top of a LEMP stack and I am trying to import orders from the website into our CRM using created_at date time of the order (so we can carry out delta updates).
The server's timezone is Europe/London and my php-fpm pool config (for my site) is said to be the same also:
php_admin_value[date.timezone] = Europe/London
I created an order and it correctly shows when the order was created at, for example:
However, if I looked at this order in the database, the created_at is set to one hour earlier (leads me to believe the BST timezone setting isn't in effect):
Does this mean Magento doesn't support BST? or is our magento setup incorrectly? or do I need a workaround (i.e. detect if daylight saving is on, then add/remove hour etc...)?
Update
This is how I have implemented give me all the orders since my last sync functionality, where $API_Data in the code below refers to last sync from server:
private function GetNewOrderIncrementIds($API_Data = '')
{
// Init
$now = new DateTime();
// Set Timezone to Europe/London (From Config)
$now->setTimezone(new DateTimeZone(Mage::getStoreConfig('mymodule_config/system_config/default_timezone')));
// Generate Date & Time
$fromDate = $API_Data;
$toDate = $now->format('Y-m-d H:i:s');
// Load Straight Order Sync Config
$sos_enabled = ((int)Mage::getStoreConfig('mymodule_config/order_sync/straight_order_sync_enabled'));
$sos_storeid = (int)Mage::getStoreConfig('mymodule_config/order_sync/straight_order_sync_storeid');
$sos_shipping = Mage::getStoreConfig('mymodule_config/order_sync/straight_order_sync_shippingmethod');
// Load Order Collection
$order_collection = Mage::getModel('sales/order')
->getCollection()
->addAttributeToFilter('created_at', array(
'from' => $fromDate,
'to' => $toDate
));
// Build Order Increment Id List
$new_orders = array();
foreach ($order_collection as $order)
{
// Check If This Order Is Straight Order Sync
$doSOS = ($sos_enabled &&
(int)$order->getStoreId() == $sos_storeid &&
$order->getShippingMethod() == $sos_shipping);
// Append Order
$new_orders[] = array(
'OrderNumber' => $order->getIncrementId(),
'DoSOS' => $doSOS
);
}
$order_collection = null;
// Finished
$this->API_Response(false, '', json_encode(array(
'LastSync' => $toDate,
'NewOrders' => $new_orders
)));
}
Magento sets script’s time relative to server time, converted to UTC. So each Magento store (database-wise) is synced to UTC. Read more # Guide through Magento’s timezones
To save created_at date use
Mage::getSingleton('core/date')->gmtDate()
To retrieve created_at store date use
Mage::helper('core')->formatDate($this->getCreatedAtStoreDate(), $format, true);
see /app/code/core/Mage/Core/Block/Abstract.php
To get order date
foreach ($order_collection as $order)
{
...
$created_at = Mage::helper('core')->formatDate($order->getCreatedAt(), 'medium', true);

ZF2 validating date and time format PT_BR always The input does not appear to be a valid date

Project utilizing ZF2 + Doctrine 2.
I Tried many formats. I'm working with a Form without validation.
My last try was:
$traindate = new Element\DateTime('trainDate');
$traindate->setAttributes(array(
'name' => 'trainDate',
'id' => 'trainDate',
'size' => '30',
'class' => 'datepicker',
'options' => array(
'label' => '',
'format' => 'd-m-Y H:i'
),
));
I need to use a input to set a date and time of a event. On Brazil the basic format is:
14-05-2014 14:20
15-05-2015 15:00
With means Days Months Year Hour Minutes, like I'm expressing on the Options -> Format.
This way always when I try to insert, i get the following messsage:
The input does not appear to be a valid date
Removing the format, i can only pass by $form->isValid($data) by Y-m-d (American Format), but by the way i can't pass time to date too, which is causing me big troubles.
I need to set date PT_BR on Form/Input, Pass by validation, Convert Data do Mysql Format (YYYY-mm-dd HH:ii:ss).
And then retrive from db and convert back to pt_br format.
But not even i can pass time with date to zf2 form, ever this error message.
I remove all filters from this form trying to get work, but doesn't work.
Where is the main problem?
After a long time paying my attention to this problem I found the right and quick solution.
After 6 month making science, I got:
Right all:
$traindate = new Element\DateTime('trainDate');
$traindate->setAttributes(array(
'name' => 'trainDate',
'id' => 'trainDate',
'size' => '30',
'class' => 'datepicker',
));
$traindate->setFormat('d/m/Y'); //ONLY WORKS ON THIS FORMAT.
Docs and people over internet don't make it clear, but to set Format only works on this form.
And to grab this to Entity, you need to write your own Hydrator extending the DoctrineHydrator:
namespace Application\Hydrator;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject;
class MyCustomHydrator extends DoctrineObject {
protected function handleTypeConversions($value, $typeOfField)
{
if($typeOfField == 'datetime'){
return \DateTime::createFromFormat('d/m/Y', $value);
}
return parent::handleTypeConversions($value, $typeOfField);
}
}
It's make it simple to work with any date format. You can extend further making Locale assertions on this Custom Hydrator as you want.
I recommend you to do the date conversion work in your Train entity. The trainData's property getter and setter could be:
//THE PROPERTY IS IN MYSQL FORMAT, BUT THE GETTER WILL RETURN IT ALWAYS IN THE BRAZILIAN ONE
public function getTrainDateTime() {
return $this->trainDateTime->format( 'd/m/Y H:i' );
}
//IT WILL ALWAYS RECIEVE A BRAZILIAN DATETIME, CONVERT IT TO MYSQL FORMAT
public function setTrainDateTime( $trainDateTime ) {
$time = \DateTime::createFromFormat( 'd/m/Y H:i', $trainDateTime )->getTimestamp();
$this->trainDateTime = new \DateTime( date( 'Y-m-d', $time ) );
return $this;
}
If you do it this way, you can always work freely with brazilian dates, without worring about formats. The dirty work will be done by the entity class.

How to set current date and time in table field using zend

I am having table called users with following fields ,
is_login(tinyint(1)) and last_login(datetime).
Below is the piece of code to update when user is online using Zend,
public function updateLastLoginDetails($id){
$currentDateTime = date('Y-m-d H:i:s');
$data = array('is_online' => 1,'last_login'=>$currentDateTime);
$this->_db->update( 'users', $data,'id = '.$id);
}
Here i am using $currentDateTime = date('Y-m-d H:i:s'); to store current data and time. But it seems not ok with time.
Kindly suggest me the best way to store current data and time using Zend .
Thanks in Advance,
Dinesh Kumar Manoharan
I'm not exactly sure what's causing your problem, but I find using NOW() to be easier. Also, you should ensure the variable $id gets quoted in the update's where condition.
public function updateLastLoginDetails($id){
$data = array('is_online' => 1, 'last_login' => new Zend_Db_Expr('NOW()'));
$this->_db->update('users', $data, array('id = ?' => $id));
}
It looks like you forgot to use $data anywhere in your code!
public function updateLastLoginDetails($id){
$currentDateTime = date('Y-m-d H:i:s');
$data = array('is_online' => 1, 'last_login'=>$currentDateTime);
$this->_db->update('users', $data, 'id = '. (int)$id);
}
You might want to consider using a TIMESTAMP field in place of a DATETIME for last_login and have MySQL update it automagically.
Hi am I understanding correctly that the year month and day are being inserted correctly but not the hour minutes and seconds? If that is the case can you please provide use with a describe of the users table. Just execute "DESCRIBE users" in phpMyAdmin.
If that is the case it could be that the field is of type DATE and not DATETIME.

Categories