I have a $date and $time fields that are stored in my db, I would like to know how can I format these fields to display them in a different format?
e.g.
2010-05-09 -> 9th May 2010
and
13:00:00 -> 1:00PM
I have tried to use carbon but it returns the following error:
InvalidArgumentException in Carbon.php line 414: Unexpected data
found. Data missing
You can always use PHP's strtotime() function and then manipulate the structure using date() as seen below.
$dateString = strtotime("2010-05-09");
$date = date("jS F, Y" ,$dateString);
echo $date;
$timeString = strtotime("13:00:00");
$time = date("g:i A" ,$timeString);
echo $time;
FWIW, I didn't realize you said specifically in Laravel. But I typed it all out, so figured I'd share anyways. Carbon (as mentioned above) may handle this in a similar fashion.
You have to use the createFromFormat method:
$time = Carbon::createFromFormat('H:i:s', '13:00:00')->format('g:iA');
The first argument is the format of the date in your string.
Related
I'm working with Laravel 5.8 and I wanted to show a popup message if the UNIX timestamp of the current date is equal to the defined Unix timestamp of the popup.
So in order to do that, I added this at the Controller:
$date1= $popup->datep; // returns 1636403400
$date1 = Carbon::createFromFormat('Y-m-d H:i:s', $date1);
dd($date1);
But instead of getting the result of $date1, I get this error:
The separation symbol could not be found Data missing
So what's going wrong here? How can I solve this issue?
You are specifying a format that is clearly not an unix timestamp. Use method for the timestamp.
$date = Carbon::createFromTimestamp($popup->datep);
If you want to compare it to be the same date, you should do the following. I don't assume you want to compare it by the hour or second, that those will almost never match.
$date->startOfDay()->eq(now()->startOfDay());
Regarding Carbon Docs:
createFromFormat() is mostly a wrapper for the base php function DateTime::createFromFormat.
which is means that your second parameter must be a valid date/time format, not a timestamp.
The DateTime::create docs:
$datetime
String representing the time.
Instead, you need to use the createFromTimestamp instantiator.
$date1 = Carbon::createFromTimestamp($date1);
I have a string "3/6/2019 3:40:19 PM" that I want to convert to a Laravel/Eloquent datetime type.
Is there a way to do that without retrieve all small pieces of the string and rebuild again to the desired format?
You can use Carbon, which is already part of any Laravel install.
http://carbon.nesbot.com/docs/#api-getters
If you have a datetime string and you want to use it with a Carbon instance you can do:
$date = \Carbon\Carbon::createFromFormat('j/n/Y g:i:s A', '3/6/2019 3:40:19 PM');
Then you can do something like:
$date->format('Y-m-d')
$date->format('H:i:s')
One line solution:
date('Y-m-d H:i:s', strtotime('3/6/2019 3:40:19 PM')));
If you want to use Laravel's Carbon you can take a look at the api docs:
I've found an example similar to your situation that also parses the 'pm'
$date = Carbon::createFromIsoFormat('!YYYY-MMMM-D h:mm:ss a', '2019-January-3 6:33:24 pm', 'UTC');
echo $date->isoFormat('M/D/YY HH:mm'); // 1/3/19 18:33
Use the PHP strtotime() function.
strToTime($string)
And if you want to change the format you can use the date() function.
date('Y-m-d H:i:s', strtotime($string))
This saves you the hassle of installing new libraries and you can change the date format in any way you want in the date function
I'm working with an XML document that is returning variables and for some reason in a xml return the timestamp is formatted like this... 20180606T110000 ... why anyone would format it like that makes no sense to me; however, its what I have to work with. ITs formatted YYYYMMDD , the T is the split between date and time, HHMMSS. ITs set up in a 24 Hour clock that I also need to convert to 12 hr clock with am/pm
I need that formatted like 06/06/2018 11:00:00 AM.
Is there a way to do that via a date format (I know how to use date() but I don't know how to bring in that timestamp the way its formatted) or even separating it out into
$year = xxxx
$month = xx
$day = $xx
$Hour=xx
etc. etc. etc.
if need be.
I've briefly looked at php's date create from format ( date_create_from_format('j-M-Y', '15-Feb-2009') ) but dont fully understand how that works.
I've also thought about a split. I've also looked at chunk_split and wordwrap but its not even amounts of characters so that would be complex to create.
Any ideas?
The format you're working with is "XMLRPC (Compact)" format. This is fully supported by PHP (you can see a list of supported formats here). To get what you want, just use a combination of strtotime() and date().
$timestring = "20180606T110000";
$timestamp = strtotime($timestring);
echo date("m/d/Y h:i:s A", $timestamp);
You can use PHP DateTime to parse a datetime String with any format. Please view the Parameters format in the following link to understand how the "Ymd\THis" part works: http://php.net/manual/en/datetime.createfromformat.php
<?php
$time = "20180606T110000";
$date = DateTime::createFromFormat("Ymd\THis", $time);
// 06/06/2018 11:00:00 AM.
echo $date->format("d/m/Y h:i:s A");
How to get date format of given string, string contain a valid date
I am try to import data from csv file, and that csv files are exported for backup
but there are so many different type of date format and in some case when i try to convert string to date it throwing me an error
ex: 04/08/2010 10:22 am
some time this type of format throwing me error
Error 500: DateTime::__construct(): Failed to parse time string
You can use just strtotime
echo date('Y-m-d H:i:s', strtotime('04/08/2010 10:22 am')); // output: 2010-04-08 10:22:00
You can use the DateTime::createFromFormat() static method.
Also, you may want to do some reading:
DateTime::__construct() reference
Supported Date and Time Formats
Date/Time extension reference
Also, you need to use the search function (top right on the page). There are a lot of questions that deal with similar problems.
Try this...........
$today = date("d/m/Y g:i a");
<?php
$today = date("d/m/Y g:i a");
echo $today;
?>
You will get output like this.........20/02/2013 7:53 am
For sample one see this example link
$data['user']['time'] = '2011-03-07 00:33:45';
how can we add 1 year to this date ?
something like $newdata = $data['user']['time'] + 1 year ?
or
$newdata = 2012-03-07 00:33:45
Thanks
Adam Ramadhan
strtotime() is the function you're looking for:
$data['user']['seal_data'] = date('Y-m-d H:i:s', strtotime('+1 year', strtotime($data['user']['time'])));
First, you have to convert the MySQL datetime to something that PHP can understand. There are two ways of doing this...
Use UNIX_TIMESTAMP() in your query to tell MySQL to return a UNIX timestamp of the datetime column.
SELECT whatever, UNIX_TIMESTAMP(myTime) AS 'myUnixTime' FROM myTable;
Use DateTime::createFromFormat to convert your string time to something PHP can understand.
$date = DateTime::createFromFormat('Y-m-d H:i:s', $data['user']['time']);
Once that is done, you can work with the time... Depending on the method you used above, you can use one of the following.
If you have a unix timestamp, you can use the following to add a year:
$inAYear = strtotime('+1 year', $data['user']['unixTime']);
If you have a DateTime object, you can use the following:
$inAYear = $date->add(new DateInterval('P1Y'));
Now, to display your date in a format that is respectable, you must tell PHP to return a string in the proper format.
If you have a unix timestamp, you can use the following:
$strTime = date('Y-m-d H:i:s', $inAYear);
If you have a DateTime object, you can use the following:
$strTime = $inAYear->format('Y-m-d H:i:s');
Alternatively, if you don't want to deal with all of that, you can simply add one year when you query.
SELECT whatever, DATE_ADD(myTime, INTERVAL 1 YEAR) AS 'inAYear' FROM myTable;
Current (2017) Practice is to use DateTime
This question is top on a google search for "php datetime add one year", but severely outdated. While most of the previous answers will work fine for most cases, the established standard is to use DateTime objects for this instead, primarily due strtotime requiring careful manipulation of timezones and DST.
TL;DR
Convert to DateTime: $date = new DateTime('2011-03-07 00:33:45', [user TZ]);
Use DateTime::modify: $date->modify('+1 year');
Format to needs.
Change the timezone with DateTime::setTimezone from the list of supported timezones: $date->setTimezone(new DateTimeZone('Pacific/Chatham'));
Convert to string with DateTime::format: echo $date->format('Y-m-d H:i:s');
Following this pattern for manipulating dates and times will handle the worst oddities of timezone/DST/leap-time for you.
Just remember two final notes:
Life is easier with your system timezone set at UTC.
NEVER modify the system timezone outside of configuration files.
I've seen too much code that relies on date_default_timezone_set. If you're doing this, stop. Save the timezone in a variable, and pass it around your application instead, please.
More Reading
How to calculate the difference between two dates using PHP?
Convert date format yyyy-mm-dd => dd-mm-yyyy
PHP - strtotime, specify timezone
I think you could use strtotime() to do this pretty easily. Something like:
$newdata = date('c', strtotime($data['user']['time'] . ' +1 year'));
Though the 'c' format string isn't the same as your input format. You could consult date()'s docs for how to construct the correct one.
'Y-m-d H:i:s' — as Tim Cooper suggests — looks correct.
This should do the trick (not tested).
$data = "2011-03-07 00:33:45";
echo 'Original date +1 year: ' . date('Y-m-d H:i:s', strtotime(date("Y-m-d H:i:s", strtotime($data)) . " +1 year"));
First-of-all if your date format is separated by a slash (/), like '2019/12/31' then you should convert it in dash (-) format, like '2019-12-31', to do so use str_replace() function.
$string = str_replace('/', '-', '2019/12/31'); //output: 2019-12-31
To add time/day/month/year do not use strtotime() function, because it can't add a time which is beyond year 2038.
So here I would prefer to use DateTime() function.
$string = '2000-01-01';
$date = new DateTime($string);
$date->add(new DateInterval('P60Y5M2DT6H3M25S')); //60 Years 5 Months 2 Days 6 Hours 3 Minutes 25 Seconds
echo $date->format('Y-m-d H:i:s'); //output: 2060-06-03 06:03:25