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.
Related
I want to use a date in my formbuilder.
When I dump the variable $date I get the output:
DateTime #1536139353 {#2479 ▼
date: 2018-09-05 11:22:33.0 Europe/Paris (+02:00)
}
When I try to use it now in my formbuilder like this:
$options['format'] = 'dd.MM.yyyy';
$options['data'] = new \DateTime($date);
Then I get an error message:
DateTime::__construct() expects parameter 1 to be string, object given
You can use just strtotime
echo date('Y-m-d H:i:s', strtotime($your_date_string));
or you can use the DateTime::createFromFormat() static method.
i hope that help you
Explanation
The DateTime is an object, you will need to get the formatted string from the object here.
Fortunately the DateTime object provides the method format() which is used to return the date/time as a string in the desired format.
In this example d.m.Y, which would output 16.04.2020.
(new \DateTime($date))->format('d.m.Y');
Your use case
It seems you are using $date which is already a DateTime object to create a new DateTime object. This won't work and is not necessary.
Since $date is already an instance of \DateTime, you can directly use
$options['format'] = 'dd.MM.yyyy';
$options['data'] = $date->format('d.m.Y');
Sources
Format
To choose the desired format, look into the documentation here
https://www.php.net/manual/de/function.date.php
DateTime Object
You must pass an interpretable string of a date while constructing.
https://www.php.net/manual/de/class.datetime.php
$date is already a datetime:
DateTime #1536139353 {#2479 ▼
date: 2018-09-05 11:22:33.0 Europe/Paris (+02:00)
}
So there is no need to convert it like this new \DateTime($date);
The solution is:
$options['format'] = 'dd.MM.yyyy';
$options['data'] = $date;
My collection structure is as:
{a,b,time}
I am inserting data in the collection through a java service where a and b are integers and time is Date field.
On selecting a field from php I am getting the response as following:
Array
(
[0] => Array
(
[b] => 19511297
[time] => Array
(
[$date] => Array
(
[$numberLong] => 1516688016000
)
)
)
)
How to get the time in the format as through the php function date('Y-m-d H:i:s) ?
Seems like your epoch timestamp is in milliseconds, so you need to do something like this:
$array[0]['time']['$date']['$numberLong'] = 1516688016000;
$timestamp = $array[0]['time']['$date']['$numberLong'] / 1000;
echo date("Y-m-d H:i:s", $timestamp);
It looks like $numberLong contains unix-timestamp, hence you can try something like this:
$data[0]['time']['$date']['date'] = date(
'Y-m-d H:i:s',
$data[0]['time']['$date']['$numberLong'] / 1000
);
You have to use correct MongoDB library first.
When you will extract data from database a datetime field in PHP would be represented as UTCDateTime.
When you had it converted to array it was like ['$date']['$numberLong']. But you don't have to do that.
When you will get a list of documents from your collection, you can iterate over cursor and extract date and time in any convenient format using toDateTime() method in conjunction with format() later.
Look at the example below:
$cursor = $collection->find([]);
foreach ($cursor as $doc) {
echo "\n" . $doc['time']->toDateTime()->format("Y-m-d H:i:s");
}
One of advantages here is that you are not loosing accuracy. The other advantage is that you can deal with timezones in a very efficient way.
For example, if you want to display date and time in IST timezone, you can do it like this:
$timezone = new DateTimeZone('Asia/Kolkata');
foreach ($cursor as $doc) {
echo "\n" . $doc['time']->toDateTime()->setTimeZone($timezone)->format("Y-m-d H:i:s");
}
I recommend you to take a look at Robo 3T (formerly Robomongo), it will help you to work with MongoDB.
I am using DateTime function of php. I get a date from a calendar in format d-m-Y and pass it via ajax to my function. I am getting the date right till this step.
When I try to store the date in unix format using:
$ai_ff_date=DateTime::CreateFromFormat('d-m-Y', $data['date']);
$final_date=$ai_ff_date->format('U');
The date stored is wrong. Suppose the date I passed via ajax is 26-12-2016 then in database 27-12-2016 is stored. Why its counting one more day then the input.
use this code :
$date = date('Y-m-d H:i:s', strtotime('-1 day', $stop_date));
$ai_ff_date=DateTime::CreateFromFormat('d-m-Y',$date);
$final_date=$ai_ff_date->format('U');
and please check the variable (code not tested)
You might want to convert the Date-Format to "Y-m-d" First and then call-in the DateTime() Constructor. However, since what you are trying to do is just get the TimeStamp you might also do that directly without using DateTime. The Snippet below shows what is meant here:
<?php
$data = ['date'=>"13-12-2016"]; //<== JUST AN EXAMPLE FOR TESTING!!!
// SIMPLY CONVERT THE DATE TO Y-m-d FIRST.
$dateYMD = date("Y-m-d", strtotime($data['date']));
// THEN USE DateTime CONSTRUCTOR TO CREATE A NEW DateTime INSTANCE
// AND THEN RUN THE FORMAT YOU WISH::
$final_date = (new DateTime($dateYMD))->format('U');
var_dump($final_date); //<== YIELDS: string '1481583600' (length=10)
var_dump(date("Y-m-d", $final_date)); //<== YIELDS: string '2016-12-13' (length=10)
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.
thanks for reading.
Just need to know how i convert datetime gotten from my sql tables in gmtime to datetime in user timezone.
the following is my code but doesn't seem to work..
//WHERE $post_arr[5] is date from sql
$user_date=convert_date_for_user($post_arr[5]);
function convert_date_for_user($date_time){
$user = JFactory::getUser();
$db = JFactory::getDBO();
$timezone=$user->getParam('timezone');
echo $tz_offset;
$user_date = JFactory::getDate($date_time,$timezone);
$user_date_str = $user_date->toUnix(true);
return $user_date_str;
}
It converts but I'm getting all the wrong time from the above code.
The simplest way to do it:
$useUserTimeZone = true;
JHtml::date($sqlGmtTimestamp , 'D F n, Y', $useUserTimeZone);
$sqlGmtTimestamp takes GMT timestamp/datetime
$useUserTimeZone is a flag to use user's timezone, otherwise server's timezone will be used.
more details here: http://docs.joomla.org/API16:JHtml/date
You don't specify your Joomla version but, did you try Joomla's JDate class directly?
// Get the User and their timezone
$user = JFactory::getUser();
$timeZone = $user->getParam('timezone', 'UTC');
// Create JDate object set to now in the users timezone.
$myDate = JDate::getInstance('now', $timeZone);
// Gets the date as UNIX time stamp.
$myDate->toUnix():
// For your example using a method
function convert_date_for_user($date_time)
{
// Get the User and their timezone
$user = JFactory::getUser();
$timeZone = $user->getParam('timezone', 'UTC');
// Create JDate object set to now in the users timezone.
$myDate = JDate::getInstance($date_time, $timeZone);
return $myDate->toUnix();
}
This is the function that works for me:-
//WHERE date_time is the format of the date taken directly from database(ie: 0000-00-00 00:00:00)
function convert_time_zone($date_time){
$user =& JFactory::getUser();
$db = JFactory::getDBO();
$timezone=$user->getParam('timezone','UTC');
$time_object = new DateTime($date_time, new DateTimeZone('UTC'));
$time_object->setTimezone(new DateTimeZone($timezone));
$user_datetime=$time_object->format('Y-m-d H:i:s');
//SELECT ONLY 1 line below
return $user_datetime; //WOULD RETURN DATETIME IN 0000-00-00 00:00:00
//OR
return $time_object->getTimestamp(); //WOULD RETURN DATETIME IN UNIX TIMESTAMP
}
Its a little out of the way as i was hoping to use functions included in the joomla API to do it. If anyone could provide a better solution please do. and i select it as the right answer.
With Joomla 2.5+ (i think), you can use the following code
echo JHtml::_('date', $input, $format, $tz, $gregorian);
$input can be one of the following values:
"now" for the current time (DEFAULT)
A date/time string in a format accepted by date()
$format can be one of the following values:
NULL to use the default locale based format (DEFAULT)
A date format specification string (see http://php.net/manual/en/function.date.php)
$tz can be one of the following values:
TRUE to use the user's time zone (DEFAULT). Note: If the user's time zone is not set then the global config time zone is used.
FALSE to use global config time zone
NULL for no conversion
A timezone string (eg: "America/Los_Angeles", see http://php.net/manual/en/timezones.php)
$gregorian can be one of the following values:
TRUE to use Gregorian calendar
FALSE to NOT use Gregorian calendar (DEFAULT)
Having tried all the given possible solutions here and not getting the date in the user's timezone (Joomla! v.3.9.14), here's my (proven) solution:
$oUser_TZ = JFactory::getUser()->getTimezone();
$aUser_tz = (array)$oUser_TZ; // almost sure this step is not that necessary
$full_date = JFactory::getDate('now', $aUser_tz['timezone']); // pretty sure $oUser_tz->timezone will work
// I had try to use $full_date->Format('Y-m-d H:i:s') but it was giving me the non-converted-to-wanted-timezone date, so
$date_converted = substr($full_date, 0, 19);
date_converted gives me the date in format Y-m-d H:i:s and in the wanted timezone.
Try This:
$date = JFactory::getDate(); // now - 2014-03-11 08:45:22
$date->setOffset(8); // UTC+8
echo $date->toMySQL(); // wrong - 2014-03-11 08:45:22
echo '<br />';
echo $date->toFormat(); // right - 2014-03-11 16:45:22
JHtml::date($post_arr[5]);
If you want a different format, use the second parameter:
JHtml::date($post_arr[5], DateTime::RFC2822);
Which is equivalent to:
1. Create a JDate object with an UTC date read from the database
2. Get the correct Time Zone in Jomla Global Configuration and User Configuration
3. Call setTimeZone() to convert your JDate object to user local time
4. Call format() to format the JDate object as a well formatted string