I'm struggling with the PHP DateTime & DateTimeZone combo: What i want to achieve is, if current datetime matches a value in this format - "H:i" a block of PHP code to be executed. So far, i've managed to arrive at this "solution", however i'm struggling to make it work:
$datetime = new DateTime();
$timezone = new DateTimeZone('Europe/Sofia');
$datetime->setTimezone($timezone);
if($datetime == '06:00') {
DB::table('shifts')->insert(['shift_number' => '1', 'created_at' => $datetime, 'updated_at' => $datetime]);
}
I'm fairly new to PHP and i would greatly appreciate any help on the matter, thanks!
You can format the dateTime object and then compare the formatted value.
Example:
if($datetime->format('H:i') === '06:00') {
echo 'match';
}
Related
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.
I'm experiencing a weird problem.
I'm using Carbon for dates. I want to use the format Y-W (year,week) which is working correctly.
Here i store it into the DB:
$weekDate = Carbon::createFromFormat('d-m-y', "{$key}")->format('Y-W');
DB::table('backorder_voorspelling')->insert([
'artikelcode' => $articlecode,
'week' => $weekDate,
'aantal' => $value,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
]);
The database record is correct:
{#426 ▼
+"id": 1
+"artikelcode": "articlecode"
+"week": "2017-44"
+"aantal": "6"
+"created_at": "2018-01-18 11:46:45"
+"updated_at": "2018-01-18 11:46:45"
}
Later on i want to convert the Y-W back to a carbon time and this is telling me:
The code i use to create the carbon time:
$startOfWeek = Carbon::createFromFormat('Y-W', $row->week);
The formats are the same, when storing i use the format ('Y-W') and when creatingFromFormat i use the format ('Y-W'), yet it's not working...
I tried replacing the - for / but this returns the same error.
Any help is appreciated.
Not all date format characters can be used in DateTime::createFromFormat (which is what Carbon extends). Unfortunately for you, W is one of the ones that's missing.
From the manual:
The format that the passed in string should be in. See the formatting options below. In most cases, the same letters as for the date() can be used.
You can work round this by manually calling setISODate on a new DateTime (or Carbon) instance:
list ($year, $week) = explode('-', '2017-44');
$d = new DateTime;
$d->setISODate($year, $week);
setISODate also accepts a third $day parameter - by default it will set to the first day of the week, which I think is what you want.
See https://eval.in/937360
I am using the fullCalendar plugin/directive in Angular, and I am currently having an issue when trying to save the date/time into my database.
These are the values being posted to my server:
{"title":"Hey","start":"2015-08-13T00:00:00.000Z","end":"2015-08-13T00:00:00.000Z","allDay":true}
Now in my controller I try to convert both date/time string into valid date/time format before saving into my database:
public function store(ScheduleRequest $request)
{
$schedule = new Schedules;
$schedule->allDay = $request->allDay;
$schedule->start = strtotime(date('Y-m-d H:i:s', $request->start));
$schedule->end = strtotime(date('Y-m-d H:i:s', $request->end));
$schedule->title = $request->title;
if ($schedule->save())
{
return [
'success' => 'Data Was Saved Successfully'
];
}
}
This is the error I get:
A non well formed numeric value encountered
I would like to know how to convert both datetime values into valid datetime objects in PHP using the specified format.
strtotime is converting a string into a timestamp and date is converting a timestamp into a string, you need to reverse date with strtotime like so:
public function store(ScheduleRequest $request)
{
$schedule = new Schedules;
$schedule->allDay = $request->allDay;
$schedule->start = date('Y-m-d H:i:s', strtotime($request->start));
$schedule->end = date('Y-m-d H:i:s', strtotime($request->end));
$schedule->title = $request->title;
if ($schedule->save())
{
return [
'success' => 'Data Was Saved Successfully'
];
}
}
Edit: Sorry, strtotime doesn't do what I thought it did, looks like you want DateTime::createFromFormat to create a DateTime object from a String and then you can go to a unix timestamp from there.
Adding strtotime($mydateValue) fixed it for me.
I have a datetime string which I would like to crop the 'time' part out of.
I need to do some calculation on it so I need to convert it to Unix time stamp.
What I've tried:
Use substr, and then strtotime, but when checking the result back to a human readable time format, it is not the same as the original date.
function convert($dbTime){
$createDate = new DateTime($dbTime);
$strip = $createDate->format('Y-m-d');
$yearMonthDateArray = explode("-", $strip);
}
The explode here crashes.
Edit:
This is the value of dbTime: "2014-07-27 12:06:00"
I want it to be "2014-07-27", and then have strototime on this format. This does not work. Converting it back to human readable date it generates 2014-07-06
Regarding comments:
I have tried all sorts of datetime functions. They either crash or they don't return the proper time
Explode crashes - it doesn't continue to the next line of code.
Edit2:
This is what's going on next. This returns false
$timeWithMakeTime = mktime(0,0,0,(int)$yearMonthDateArray[0], (int)$yearMonthDateArray[1],(int)$yearMonthDateArray[2]);
Discarding all your messy code, I assume you just want this:
$dbTime = '2014-07-27 12:06:00';
$date = new DateTime($dbTime);
$date->setTime(0, 0, 0);
echo $date->getTimestamp();
DateTime is an object, so what if you want to get timestamp you can do is as follows:
function convert($dbTime){
$createDate = new DateTime($dbTime);
return $createDate->getTimestamp();
}
You can read more about getTimestamp and other DateTime functions
Make sure your variable $dbTime is in correct format. For example DateTime does not support split seconds.
$date = date('H:i:s', strtotime($dbTime));
echo $date;
I want to use this Carbon function:
Carbon::now()->subDays(5)->diffForHumans()
And I need to create the correct integer.
I am loading a string with a Datetime, which I want to subtract in Laravel like this:
$datetime = $score->created_at;
Then I save the current Time into a variable
$now = Carbon::now()->toDateTimeString();
This is what I get:
echo $now . '<br>'; // 2014-07-13 22:53:03
echo $datetime; // 2014-07-12 14:32:17
But when I want to subtract one from another I get the following error:
echo $now - $datetime;
Object of class Carbon\Carbon could not be converted to int
Any help here would be greatly apreciated.
I know it's a bit late, but this works:
$score->created_at->diffForHumans(\Carbon\Carbon::now())
If you want to change the date format just use the format function
$now = Carbon::now();
$score->created_at->diffForHumans($now)->format('Y-m-d');