Format a date in PHP - php

How can i use the format methode in the Class DateTime in PHP and take some format like :
'Y-m-d H:i' or just the date 'Y-m-d'.
this my code and i putted a picture what i take when i do the dump :
$thisday = new \DateTime(); // I want to take the system date is it ok this instruction ?
$thisday->format('Y-m-d');
dump($thisday);
die();
How can i take just the 2016-04-21 ?
Or take the date, hour and minutes ?

format() does not transform the original DateTime object into your formatted result, it simply returns your formatted result, which you are not assigning to anything. You need to assign
$thisday->format('Y-m-d');
to a new variable, and use that.

You need to assign the result a variable. DateTime::format is returning the value, not changing the object itself
$str = $thisday->format('Y-m-d');
dump($str);

Related

Laravel - format date to store it on MySQL database

I am using Laravel and I have to get some dates and store it on MySQL database.
When I create the date like this:
$date_sol = Carbon::createFromFormat("Y-m-d H:i:s","2020-12-10 01:00:00");
The date is properly stored on the database. However, I have to get the date from an input.
I am trying to get the date and then format it like this:
$novaData = $request->input('solicitacao_data') . ' 15:16:17';
$sol->data = Carbon::parse($novaData)->format("Y-m-d H:i:s");
However, I get the error:
DateTime::__construct(): Failed to parse time string (28/03/2020
15:16:17) at position 0 (2): Unexpected character
The error is at the line $sol->data = Carbon::parse($novaData)->format("Y-m-d H:i:s");
How do I make the formating conversion properly? I am new using Laravel. I am not sure about it.
For date format 'd/m/Y' try this.
Carbon::createFromFormat('d/m/Y', '22/02/2020')->toDateTimeString();
Similarly for date format Y-m-d try this
Carbon::createFromFormat('Y-m-d', '2020-02-22')->toDateTimeString();
output will be in format (Y-m-d H:i:s)
"2020-02-22 21:05:13"
Let's say you receive something as input.
Well, ideally you should first sanitize it, to make sure you received a string that can be interpreted as a date. For that, I would suggest you to have a look there :
php date validation
So, you assign the input to a var and append a string representing some time to it:
$novaData = $request->input('solicitacao_data'). ' 15:16:17';
From here, the easiest is to convert the string into a timestamp. Which can be achieved this way:
$time = strtotime($novaData);
And now, you can use Carbon to format the date the way you want :
$sol->data = Carbon::createFromTimestamp($time)->format("Y-m-d H:i:s");

PHP convert string into date time

I have a php string from db it is 20/11/2017 I want to convert it milliseconds.
It's my code to doing that.
$the_date = "20/11/2017";
$mill_sec_date = strtotime($the_date);
var_dump($mill_sec_date);
But it does not print any thing rather than
bool(false);
What is the problem and how can i solve it ????
When using slashes to separate parts of the date, PHP recognizes the format as MM/DD/YYYY. Which makes your date invalid because there is no 20th month. If you want to use the format where day and month is swapped, you need to use hyphens, like DD-MM-YYYY.
$time = strtotime('10/16/2003');
$newformat = date('Y-m-d',$time);
print_r($newformat);
Use DateTime class to call function createFromFormat
$date = date_create_from_format('d/M/Y:H:i:s', $string);
$date->getTimestamp();
Most likely you got the date format wrong, see
here for a list of supported date and time formats:
This section describes all the different formats that the strtotime(), DateTime and date_create() parser understands.
You string is not accept by the strtotime, you can use createFromFormat set set the with the format type of the time string like below, you can also check the live demo. And you also can refer to this answer
var_dump(DateTime::createFromFormat('d/m/Y', "20/11/2017"));

How to format date in PHP from a string of concatenated numbers?

I am new to PHP and I am trying to learn more of php date and time but I seem to get stuck with this.
I have this date format:
ddMMyyHHmmss
And an example is 120813125055 but I am trying to manipulate the string such that it will give me the format of:
yyyy-MM-dd HH:mm:ss (in the example above, 2013-08-12 12:50:55)
I tried to do something like:
date('Y-m-d H:i:s', strtotime('120813125055'));
But it always gives me a result of 1969-12-31 18:00:00.
I assume that I need to do some string manipulation in PHP for this but I was wondering if there is an easier and more efficient way to do it?
I think what you're looking for is in the second response answered here: how to re-format datetime string in php?
To summarize (and apply to your example), you could modify the code like this.
$datetime = "120813125055";
$d = DateTime::createFromFormat("dmyHis", $datetime);
echo $d->format("Y-m-d H:i:s");
Use date_create_from_format:
$ts = date_create_from_format('dmyHis', '120813125055');
$str = date('Y-m-d H:i:s', $ts);
strtotime() only works on EASILY recognizable formats. Your is a ugly mix of garbage, so no surprise that strtotime bails with a boolean FALSE for failure, which then gets typecast to an int 0 when you tried feed it back into date().
And of course, note that your time string is NOT y2k compliant. two digit years should never ever be used anymore, except for display purposes.
You're using your function call and the argument the wrong way around.
In your example, php will try to return you the date for which the time is 'strtotime('120813125055')', and this function returns false (interpreted as 0). So you get returned the date formatted in 'Y-m-d H:i:s' for the Unix epoch.
You will need to get the actual timestamp of your string, so use http://www.php.net/manual/en/datetime.createfromformat.php.
You are mistaken here..
I tried to do something like:
date('Y-m-d H:i:s', strtotime('120813125055'));
You shouldn't use only numbers ( doesnt matter its an integer or a string ), than it will always give you the same thing.
You can use any other valid date and time ( E.G. 6 Jun 2013, 5 may 12...) . Because what strtotime() do is detect a valid date and convert it into timestamp.

Convert or Extract Year, Month and Date from a string in PHP

All,
I have the following string:
$dateTime = '2013-09-15T00:00:00.000Z';
Is there a function to extract Year, Month and Date from the above string, so the result looks like the following:
$yearMonthDate = '2013-09-15';
Thanks
You could convert your datetime to a timestamp using strtotime() and then convert it back into a formatted date using this kind of syntax:
date("Y-m-d", strtotime($myOriginalDate))
substr or DateTime or strtotime+date
Since the first string is actually a standard, you can just use substr:
$yearMonthDate = substr($dateTime, 0, 10);
However, that would be kind of a hack and would obviously break if the format of $dateTime were to change. So, you might want to look into the PHP DateTime class instead.

How to echo a formatted date in PHP from an array

I have a datetime column in MySQL let's call it $time. It's coming form a CakePHP form. If I try to echo it I get I just get "Array". If I print_r() on it I get:
Array ( [month] => 10 [day] => 30 [year] => 2010 [hour] => 16 [min] => 30 )
I want to echo this out as a formatted date, nothing seems to work because it's not a string but an array. Do I have to go like this:
echo $time['month'].'-'.$time['day'].'-'.$time['year'].' '.$time['hour'].':'.$time['min'];
or can I use the date function?
One simple, procedural way is to use date() in conjunction with mktime(), like so. date() formats based on a UNIX timestamp; mktime() provides a timestamp based on your array values:
$timestamp = mktime($time['hour'], $time['min'], 0, $time['month'], $time['day'], $time['year']);
echo date('M-d-Y H:i', $timestamp);
For a more object-oriented approach with the DateTime class, refer to Gordon's answer.
You can do:
$dt = new DateTime;
$dt->setDate($time['year'], $time['month'], $time['day']);
$dt->setTime($time['hour'], $time['minute']);
echo $dt->format(DateTime::ISO8601);
You can put any format into format() that is also supported with date().
You do not need PHP5.3 for this.
Use the above if you need to create a date that is not already contained in the array. If you simply want a 'Y-m-d H:i' format, you can use
printf("%d-%02d-%02d %02d:%02d",
$time['year'], $time['month'], $time['day'],
$time['hour'], $time['min']);
or with argument swapping and passing the entire array (though you have to rely on the order then):
vprintf('%3$d-%1$02d-%2$02d %4$02d:%5$02d', $time);
Needless to say, you can also use vsprintf or sprintf to create a datetime string that can be parsed with DateTime or strtotime, e.g.
$dt = new DateTime(vsprintf('%3$d-%1$02d-%2$02d %4$02d:%5$02d', $time));
which you could then format as shown in the first example.
Do I have to go like this:
That is one option, yes.
or can I use the date function?
Not with the data in the current form.
You could consider converting the array into a proper timestamp or DateTime object for maximum flexibility in formatting, calculations etc.
For a timestamp, see mktime() (You'll have to feed it the members of your array. Update: #BoltClock has an example.)
For a DateTime object - it's PHP5's new, object-oriented, Year 2038 bug-free, and much better way of dealing with dates - see CreateFromFormat() (Needs PHP 5.3+, though)
The date() function has an optional argument $timestamp. You can echo date("MM-dd-yyyy hh:mm, $time) and avoid manual formatting.
I hope the $time value is declared as TIMESTAMP in MySQL for this to work
Date function wants a timestamp. But you could use a custom function, such as:
function fd($time) {
return "$time[month]-$time[day]-$time[year] $time[hour]:$time[minute]";
}
// Sample usage
echo fd($time);
Does the Time helper not suit the needs here? Just pass the whole array to it and use the functions it provides.

Categories