PHP Combine Date and Time fields to form DateTime - php

I have 3 separate fields:
// date object in the format yyyy-mm-dd
$service_1_date
// time object in the format 00:00:00
$booking->service_1_time_start
// time object in the format 00:00:00
$booking->service_1_time_end
I have set these up as separate fields because I manipulate them separately in my application.
However as I am creating a Google Calendar event I must pass a datetime object as one value like this:
Event::create([
'name' => 'New Booking',
'startDateTime' => '',
'endDateTime' => '',
]);
In order for me to pass the startDateTime and endDateTime parameters I must first combine my date and time objects. So my question is how do I combine my date and time objects to make it into one datetime object?
it is expecting an instance of Carbon

use it like this:
$newDT = date('Y-m-d H:i:s', strtotime("$service_1_date $booking->service_1_time_start"));

Related

Getting only time from Carbon object

Im reading an excel file a column with values like "1:45:00. But when print_r($value["time"]) this value from my array I got a Carbon object like this:
Carbon\Carbon Object
(
[date] => 2018-10-30 01:45:00.000000
[timezone_type] => 3
[timezone] => America/US
)
Then, when I insert to a bulk array my value with:
"time"=>$value["time"]
In the database I got: 2018-10-30 01:45:00
How can I insert only 01:45:00 and not the entire timestamp?
EDIT: I thought that $value["time"]->date->format("H:i:s") would works but I got the error "Trying to get property 'date' of non-object"
EDIT 2: This is how I read the data:
The excel is like:
date time
---------- -------
30-10-2018 01:45:00
The code where I read the excel:
$data = Excel::selectSheetsByIndex(0)->load($path, function($reader) {
})->get()->toArray();
foreach ($data as $key => $value) {
$time = Carbon::createFromFormat('Y-m-d h:i:s',$value["time"])->format('h:i:s');
print_r($time);
die();
}
The output:
Call to a member function format() on null
What you need is the formatting here:
$dt = Carbon::now();
$dt->toTimeString(); //14:15:16
Carbon\Carbon is an extension to php's DateTime, so you can read at php.net to learn more.
Although America/US is not a valid timezone, so there's something going on with that.
Anyway,
In the database I got: 2018-10-30 01:45:00
If your data type is a TIMESTAMP or a DATETIME, mysql will always have a date component for data in that column.
First, let's get the time out of the $value array to make the rest of the discussion easier to understand and debug:
$time = $value["time"];
From here on out, pay no attention to the internal fields revealed by var_dump. They may or may not actually exist like that in the object. Use the mostly-well-documented interface methods documented in the link above or in the Carbon docs. The fields given by var_dump will just confuse you otherwise.
If you just want the time of day represented as a string, you use the DateTime::format() method:
$timestr = $time->format('H:i:s');
Note that if you insert that string in a database with a DATETIME column type, it won't work. Mysql will require a string that includes date information.
The code snippet that follows doesn't seem to match with the code you show above:
$data = Excel::selectSheetsByIndex(0)->load($path, function($reader) {
})->get()->toArray();
foreach ($data as $key => $value) {
$time = Carbon::createFromFormat('Y-m-d h:i:s',$value["time"])->format('h:i:s');
print_r($time);
}
You are trying to create a Carbon instance using the createFromFormat() method. The first parameter you provide tells Carbon (actually DateTime) what the format of your input string will be. The data you are supplying is H:i:s (assuming $value["time"] is read from the time column of your Excel sheet), but you're telling Carbon that you will be giving it Y-m-d h:i:s. Since the format you promise doesn't match the data you are giving the object, null is resulting.
Either (broken into to steps for clarity):
$time = Carbon::createFromFormat('H:i:s', $value["time"]);
$timestr = $time->format('h:i:s');
or
$time = Carbon::createFromFormat('d-m-Y H:i:s', $value["date"] . " " . $value["time"]);
$timestr = $time->format('h:i:s');
will work.
The second one gives you a Carbon object that is much more useful - the first one will probably default to year zero. In both cases the timezone will be the zone of the machine the code is running on. You can override that if necessary.
Note that if I'm confused and the Excel reader is actually returning Cabon objects rather than strings, you can eliminate the whole createFromFormat code altogether. No sense making a Carbon object out of a Carbon object.

Storing and retrieving dates in Mongodb 3.2 with PHPLIB

Using Mongo and PHP how does one store a datetime type, and then retrieve by date?
This is what I have for inserting, but it stores the date as a string:
$collection->insertOne(['date_created' => '2017-01-02 17:20:15']);
How should I be sending the date to Mongo to store as a datetime type so I can do the proper finds?
Put an instance of this class into the array: http://php.net/manual/en/class.mongodb-bson-utcdatetime.php
You need to use the BSON objects in the PHP arrays: http://php.net/manual/en/book.bson.php
Those get serialized properly before passed to Mongo.
$test = array(
"_id" => 123,
"name" => "This is an example",
"date_created" => new MongoDB\BSON\UTCDateTime(time() * 1000)
);
$collection->insert($test);
The time() is multiplied by 1000, because the constructor wants the milliseconds elapsed since the unix epoch, and time() returns the seconds elapsed since the unix epoch. See: http://php.net/manual/en/mongodb-bson-utcdatetime.construct.php
UPDATE:
To retrive the date/time in ISO format, just convert the UTCDateTime object fist to DateTime:
$date_created = $test["date_created"];
$iso_date = $date_created->toDateTime()->format("Y-m-d H:i:s");

Converting a carbon date to mysql timestamp.

I have a timestamp variable column in a mysql database. Trying to convert a carbon timestamp to something that I can input there, but Carbon::now() only returns a Carbon object and when I try to use the timestamp string of the Carbon object, it does not register in mysql.
public function store(CreateArticleRequest $request){
$input = $request->all();
var_dump($input); // JUST SO YOU CAN SEE
$input['published_at'] = Carbon::now();
var_dump($input); // JUST SO YOU CAN SEE
Article::create($input);
}
My first var dump is like so:
array (size=4)
'_token' => string 'Wy67a4hWxrnfiGz61wmXfYCSjAdldv26wOJiLWNc' (length=40)
'title' => string 'ASDFasdf' (length=8)
'body' => string 'asdfasdf' (length=8)
'published_at' => string '2015-08-26' (length=10)
My second var dump is like so.
The mysql column relating to "published_at" is a timestamp variable. How an I suppose to convert this from a Carbon Object?
Thanks in advance.
The short answer is that toDateTimeString() is what you're looking for:
$input['published_at'] = Carbon::now()->toDateTimeString();
See http://carbon.nesbot.com/docs/ for more options, including toDateString() if you just want the date part and not the time.
But an even better way to handle it would be to let Laravel handle casting the date value to/from a Carbon object for you. See https://laravel.com/docs/5.4/eloquent-mutators#date-mutators.
The problem is in your date string, for example, you have this:
public function setCrbDateAttribute($value)
{
$this->attributes['crb_date'] = \Carbon\Carbon::createFromFormat('d-m-Y h:i', $value);
}
Now, if there is a date like 10-12-2014 then this error will occur because the hour and minute is missing. So you make sure that the date contains all the pars and also make sure that the date string contains - as a separator not /.
In other words, check the $value before you use Carbon and make sure your date string contains exactly the same formatted string you've used in the method.
This also happens in an accessor method, so check the date value first before you use it in Carbon::createFromFormat().
If you are getting the date from user input then validate the date before using it using date or date_format:format rule, check the validation here.
Answer ref:
Laravel/Carbon Timestamp 0000-00-00 00:00:00 or Unexpected data found. Unexpected data found. Data missing
You can also set Mutator on your model.
public function setPublishedAt($value)
{
$this->attributes['published_at'] = strtotime($value);
}
to convert to timestamp
$model -> setPublishedAt('2015-08-26'); // 1440572400
or you can just convert the date to timestamp using strtotime
strtotime — Parse about any English textual datetime description into a Unix timestamp
Hope this help.

Symfony2: DateTime object not working

I am working with the DateTime object and have this problem to obtain the activity of a specific day.
In the controller I do the following query:
$date = new \DateTime('today');
$activity = $em->getRepository('MyBundle:myEntity')->findOneBy(array(
'activity_date' => $date
));
Result for this query is null, but when I define the parameter date in this way:
$date = new \DateTime('Wednesday, ‎January ‎14, ‎2015');
I get the activity that matches this date. Why doesn't today work?
I believe that commenter #prodigitalson is right. When you say today that is in fact now which is formatted with YYYY-MM-DD HH:MM:SS.
Now, if your DBMS column is of type date, DBMS will first normalize two values and only then proceed with comparing.
If your incoming parameter has a value of 2014-01-14 16:47:20, comparing it to DBMS value of 2014-01-14 00:00:00 will no match the record.
Try the following:
$date = new \DateTime(); // no need for explicit `today`
$date->setTime(0,0,0); // reset hours, minutes and seconds to 0
$activity = $em->getRepository('MyBundle:myEntity')->findOneBy(array(
'activity_date' => $date
));
Will this work?

How to query mongodb Date using php

I need to convert this query from php to mongoDB query
$query = "select * from table where data_added like '%data%';
I have date stored in variable
$date = "2013-09-02";
and in my mongo Document the date sorted as :
$dateAdded = new MongoDate(strtotime('2013-09-02 12:21:55'));
I tried
$date = new MongoDate(strtotime("$date"));
$mongo->find(array('date_added'=>array('$lt'=>$date)));
and
$mongo->find(array('date_added'=>$date));
but without success .
so I need to query usin (Y-m-d) not (Y-m-d h:i:s)
so how to use LIKE query for data in mongo
Thanks
You need to do a range query. Create a timestamp, for example using strtotime(), to get the unix timestamp at the start of the day, and another one and the end of the day.
Depending on if you want these two ends inclusive or exclusive, you then use
// Both points/seconds inclusive
->find(array("date" => array('$gte' => $startOfDay, '$lte' => $endOfDay)));
// Both seconds exclusive
->find(array("date" => array('$gt' => $startOfDay, '$lt' => $endOfDay)));
See http://cookbook.mongodb.org/patterns/date_range/

Categories