Getting only time from Carbon object

18,556

Solution 1

What you need is the formatting here:

$dt = Carbon::now();
$dt->toTimeString(); //14:15:16

Solution 2

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.

Share:
18,556

Related videos on Youtube

pmiranda
Author by

pmiranda

Pretty old school in some stuff (I used to own at Logo with Poly 5 with colors and making some races with them, while my old brother was ruling with Frogger, Choplifter and Dig-dug at our Atari 130XE) and newbie in others. I work (or used to in some cases) with jQuery, ReactJS 15/16/17 (FLUX, Redux, Hooks), Symfony 2-3, OpenLayers 2-3, ArcGIS JS-API 3, PostGIS, Laravel 5.1, 5.4, 5.5, 5.6, 5.8, Angular 6-7, AngularJS, NodeJS, Express, UIKit 2, Bootstrap 2,3,4, Material-UI, React Native, Lerna, Serverless framework, AWS (Cognito, DynamoDB, Lambdas, API Gateway, etc), Github Actions, CircleCI, now I'm struggling to work with MongoDB, Drone, Sonarqube. I also know a lot of nutrition (the sumo pic is not me by the way). Actually, I think I know more of nutrition than anything that I post or ask here at StackOverflow.

Updated on June 04, 2022

Comments

  • pmiranda
    pmiranda almost 2 years

    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

    • pmiranda
      pmiranda over 5 years
      So how could I get the date from it?
    • eResourcesInc
      eResourcesInc over 5 years
      Try setting a variable equal to $value["time"]. Call it $carbonObject = $value["time"]. Then try the answer I posted below. Should work if $value["time"] really is a carbon object.
    • Patrick Q
      Patrick Q over 5 years
      Can you show the code where you are actually populating $value?
    • aynber
      aynber over 5 years
      You should be able to use $value["time"]->toTimeString(), but the error you're getting is interesting unless you've manipulated it between the print_r and the rest of the code.
    • eResourcesInc
      eResourcesInc over 5 years
      Based on your answer, it seems you don't really have a carbon object. If this is the case, you create one, then use the format method afterward. I'm adding this as an edit to my answer below.
    • pmiranda
      pmiranda over 5 years
      I've already tried all the suggestions. @PatrickQ ok, I will edit my question with that part.
    • eResourcesInc
      eResourcesInc over 5 years
      Please try the answer I suggested below with Carbon::createFromFormat. It should work regardless of whether the $data["time"] is a carbon format.
    • Patrick Q
      Patrick Q over 5 years
      Your call to createFromFormat() is returning null because the format does not match the format of your time column. What was your original code that produced the errors actually mentioned in your question? How were you creating $value such that in one place is was seen as an object and in another it wasn't?
    • pmiranda
      pmiranda over 5 years
      In red is what I need to get: i.imgur.com/C5fgvY7.png
    • aynber
      aynber over 5 years
      I think you probably need to get $value[0]['time']->toTimeString(). $value is an array of objects/arrays
    • pmiranda
      pmiranda over 5 years
      Lol, with $value["date"].["date"] I got 2018-05-01 00:00:00Arrayas an Output... I don't get it
    • bishop
      bishop over 5 years
      I think you want Y-m-d H:i:s in the format string, to account for leading zeroes. (Note the capital H, versus lower h.)
  • pmiranda
    pmiranda over 5 years
    I'm using postresql, and "time" is a varchar.
  • Jerry
    Jerry over 5 years
    Then the $timestr produced by any versions of the above should be fine.