In my application,I retrieve a timestamp from the table which is of the format 2009-08-18 12:09:01. I need to change this to August 18th,2009 or 18 Aug,2009. How to achieve this in CakePHP?
Are there any built in methods?
You can use the core TimeHelper to format and test dates/times.
To use it, you need to add the TimeHelper to your controller's $helpers array:
var $helpers = array('Time');
Then from the view you can format your date/time variables:
// assuming $variable['Model']['field_name'] = '2009-09-09 12:00:00':
echo $this->Time->format('F jS, Y', $variable['Model']['field_name']);
// => 'September 9th, 2009'
echo $this->Time->format('j M Y', $variable['Model']['field_name']);
// => '9 Sep 2009'
Since this method is ultimately a wrapper, use the table in the PHP documentation for the date() function to determine how to write the format string.
As of 1.3, if you reverse the order of the parameters (date first, format second) it will try to respect the date format of your locale. The above ordering will still work for backwards compatibility. More details at the bottom of this page in the migration guide.
You can use strptime to parse the string into a datetime and then strftime to format it back into the string you want.
Use the time helper as mentioned by deizel.
I would look through the file /cake/libs/view/helpers/time.php to see if there is a function there that provides the time format you are after.
The relative time functions are especially nice:
<?php echo $time->nice($dateValue); ?>
<?php echo $time->timeAgoInWords($dateValue); ?>
You can learn a great deal from reading the CakePHP source.
This should do:
<?php echo date('M js Y', strtotime($post['Post']['date'])); ?>
Here, Post is the name of the model and date is the field name.
Related
I am using the _get_last_post_time() function to show the date of a last added post.
_get_last_post_time( $timezone, array('date','modified'), $post_type);
So far this is all clear, but the output is in 'Y-m-d H:i:s' format. How do I modify this in a different date format?
Source:
https://core.trac.wordpress.org/browser/tags/5.8/src/wp-includes/post.php#L7076
From the _get_last_post_time Docs
"This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions."
Use this function instead: get_lastpostdate Docs
get_lastpostdate will return a string. After that you could use strtotime function to convert it to time format. Then you could use date function to format its output any way you need to, for example:
$last_date = get_lastpostdate();
echo date("M d Y H:i:s", strtotime($last_date));
The above format outputs something like this:
Jul 05 2021 16:30:13
Another example:
echo date("H:i:s", strtotime($last_date));
The above format outputs something like this:
16:30:13
Here is the documentation for formatting date and time in wordpress:
Customizing the Time and Date Format in Wordpress Docs
I'm using laravel 5.5 and Carbon library to write an API.
I store all date and time values in MySQL database as common YYYY-MM-DD HH:MM:SS format.
But on the other hand front-end developer ask me to return all dates as 2017-12-20T20:30:00.000Z. seems that is a common format in JavaScript.
Is there any way to convert all DateTime formatted fields to desired format via laravel or Carbon ?
Update:
First problem is solved but another one is that client want to send date times as same 2017-12-20T20:30:00.000Z for all fields of table. while I should get and save them as common DateTime. What can I do in this case?
Javascript uses ISO 8601 syntax. In PHP, you can use like this:
date('c', strtotime($yourDateTime)); // c is ISO 8601 format
Reference here:
Since the date is casting as Carbon, use format():
$date->format($desiredFormat);
The list of characters for creating $desiredFormat will also be helpful.
Laravel Provide getter and setter method for format Eloquent attribute values
by default laravel return 'dateTime' as carbon instance
so, you can change format in model using getter method
public function getDateTimeAttribute($value)
{
$desiredFormat = "Y-M-d"; //change format as per your requirement
$value->format($desiredFormat);
}
Link for more about getter and setter method
https://laravel.com/docs/5.5/eloquent-mutators
{{ date('M j, Y h:ia', strtotime($created_at)) }}
It gives us like "Dec 30, 2017 16:39am"
You can edit you date time of course(M j, Y h:ia) just google it "php: date - manual"
This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 12 months ago.
I want to change the date format which is fetched from database.
now I got 2016-10-01{{$user->from_date}} .I want to change the format 'd-m-y' in laravel 5.3
{{ $user->from_date->format('d/m/Y')}}
Try this:
date('d-m-Y', strtotime($user->from_date));
It will convert date into d-m-Y or whatever format you have given.
Note: This solution is a general solution that works for php and any of its frameworks. For a Laravel specific method, try the solution provided by Hamelraj.
In Laravel use Carbon its good
{{ \Carbon\Carbon::parse($user->from_date)->format('d/m/Y')}}
In your Model set:
protected $dates = ['name_field'];
after in your view :
{{ $user->from_date->format('d/m/Y') }}
works
You can check Date Mutators: https://laravel.com/docs/5.3/eloquent-mutators#date-mutators
You need set in your User model column from_date in $dates array and then you can change format in $dateFormat
The another option is also put this method to your User model:
public function getFromDateAttribute($value) {
return \Carbon\Carbon::parse($value)->format('d-m-Y');
}
and then in view if you run {{ $user->from_date }} you will be see format that you want.
There are 3 ways that you can do:
1) Using Laravel Model
$user = \App\User::find(1);
$newDateFormat = $user->created_at->format('d/m/Y');
dd($newDateFormat);
2) Using PHP strtotime
$user = \App\User::find(1);
$newDateFormat2 = date('d/m/Y', strtotime($user->created_at));
dd($newDateFormat2);
3) Using Carbon
$user = \App\User::find(1);
$newDateFormat3 = \Carbon\Carbon::parse($user->created_at)->format('d/m/Y');
dd($newDateFormat3);
Method One:
Using the strtotime() to time is the best format to change the date to the given format.
strtotime() - Parse about any English textual datetime description into a Unix timestamp
The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.
Example:
<?php
$timestamp = strtotime( "February 26, 2007" );
print date('Y-m-d', $timestamp );
?>
Output:
2007-02-26
Method Two:
date_format() - Return a new DateTime object, and then format the date:
<?php
$date=date_create("2013-03-15");
echo date_format($date,"Y/m/d H:i:s");
?>
Output:
2013/03/15 00:00:00
You can use Carbon::createFromTimestamp
BLADE
{{ \Carbon\Carbon::createFromTimestamp(strtotime($user->from_date))->format('d-m-Y')}}
I had a similar problem, I wanted to change the format, but I also wanted the flexibility of being able to change the format in the blade template engine too.
I, therefore, set my model up as the following:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
\Carbon\Carbon::setToStringFormat('d-m-Y');
class User extends Model
{
protected $dates = [
'from_date',
];
}
The setToStringFormat will set all the dates to use this format for this model.
The advantage of this for me is that I could have the format that I wanted without the mutator, because with the mutator, the attribute is returned as a string meaning that in the blade template I would have to write something like this if I wanted to change the format in the template:
{{ date('Y', strtotime($user->from_date)) }}
Which isn't very clean.
Instead, the attribute is still returned as a Carbon instance, however it is first returned in the desired format.
That means that in the template I could write the following, cleaner, code:
{{ $user->from_date->format('Y') }}
In addition to being able to reformat the Carbon instance, I can also call various Carbon methods on the attribute in the template.
There is probably an oversight to this approach; I'm going to wager it is not a good idea to specify the string format at the top of the model in case it affects other scripts. From what I have seen so far, that has not happened. It has only changed the default Carbon for that model only.
In this instance, it might be a good set the Carbon format back to what it was originally at the bottom of the model script. This is a bodged idea, but it would work for each model to have its own format.
Contrary, if you are having the same format for each model then in your AppServiceProvider instead. That would just keep the code neater and easier to maintain.
I suggest using isoFormat for better appearance on the web pages.
{{ \Carbon\Carbon::parse($blog->created_at)->isoFormat('MMM Do YYYY')}}
The result is
Jan 21st 2021
Carbon Extension
In Laravel 8 you can use the Date Casting: https://laravel.com/docs/8.x/eloquent-mutators#date-casting
In your Model just set:
protected $casts = [
'my_custom_datetime_field' => 'datetime'
];
And then in your blade template you can use the format() method:
{{ $my_custom_datetime_field->format('d. m. Y') }}
In Laravel you can add a function inside app/Helper/helper.php like
function formatDate($date = '', $format = 'Y-m-d'){
if($date == '' || $date == null)
return;
return date($format,strtotime($date));
}
And call this function on any controller like this
$start_date = formatDate($start_date,'Y-m-d');
Hope it helps!
For a more natural date format used everywhere outside of the US, with time that includes hours, minutes and seconds:
07/03/2022 19:00:00
{{ \Carbon\Carbon::parse($transaction->created_at)->format('d/m/Y H:i:s')}}
Or if you'd prefer to use a more natural 12-hour-clock-based time format like this:
07/03/2022 7:00:00 PM
{{ \Carbon\Carbon::parse($transaction->created_at)->format('d/m/Y g:i:s A')}}
Here's the full list of variables available for use in the PHP/Carbon date-time format.
Sometimes changing the date format doesn't work properly, especially in Laravel. So in that case, it's better to use:
$date1 = strtr($_REQUEST['date'], '/', '-');
echo date('Y-m-d', strtotime($date1));
Then you can avoid error like "1970-01-01"!
Basically I am wondering how I would go about taking pieces of a string and putting them into another variable. I need to do this as, from API I am using, you are given the date of channel creation and I would like to take the data from this, but it is displayed in a strange way.
Here is what is given by the API:
2012-06-11T13:36:21Z seconds
^^ That is what I need to change so that I can display it in a nicer way. i.e. 11-06-2012.
Thanks.
P.S. This is twitch API if it matters.
You could use two PHP functions: "strtotime()" and "date()"
$timestamp = "2012-06-11T13:36:21Z";
echo date("jS F, Y", strtotime($timestamp));
The above would echo "11th June, 2012"
Look up the createFromFormat() function for DateTime.
I want to input a timestamp in below format to the database.
yyyy-mm-dd hh:mm:ss
How can I get in above format?
When I use
$date = new Zend_Date();
it returns month dd, yyyy hh:mm:ss PM
I also use a JavaScript calender to insert a selected date and it returns in dd-mm-yyyy format
Now, I want to convert these both format into yyyy-mm-dd hh:mm:ss so can be inserted in database. Because date format not matching the database field format the date is not inserted and only filled with *00-00-00 00:00:00*
Thanks for answer
Not sure if this will help you, but try using:
// to show both date and time,
$date->get('YYYY-MM-dd HH:mm:ss');
// or, to show date only
$date->get('YYYY-MM-dd')
Technically, #stefgosselin gave the correct answer for Zend_Date, but Zend_Date is completely overkill for just getting the current time in a common format. Zend_Date is incredibly slow and cumbersome to use compared to PHP's native date related extensions. If you don't need translation or localisation in your Zend_Date output (and you apparently dont), stay away from it.
Use PHP's native date function for that, e.g.
echo date('Y-m-d H:i:s');
or DateTime procedural API
echo date_format(date_create(), 'Y-m-d H:i:s');
or DateTime Object API
$dateTime = new DateTime;
echo $dateTime->format('Y-m-d H:i:s');
Don't do the common mistake of using each and every component Zend Frameworks offers just because it offers it. There is absolutely no need to do that and in fact, if you can use a native PHP extension to achieve the same result with less or comparable effort, you are better off with the native solution.
Also, if you are going to save a date in your database, did you use any of the DateTime related columns in your database? Assuming you are using MySql, you could use a Timestamp column or an ISO8601 Date column.
This is how i did it:
abstract class App_Model_ModelAbstract extends Zend_Db_Table_Abstract
{
const DATE_FORMAT = 'yyyy-MM-dd';
public static function formatDate($date, $format = App_Model_ModelAbstract::DATE_FORMAT)
{
if (!$date instanceof Zend_Date && Zend_Date::isDate($date)) {
$date = new Zend_Date($date);
}
if ($date instanceof Zend_Date) {
return $date->get($format);
}
return $date;
}
}
this way you don't need to be concerned with whether or not its actually an instance of zend date, you can pass in a string or anything else that is a date.
a simple way to use Zend Date is to make specific function in its business objects that allows to parameter this function the date format. You can find a good example to this address http://www.pylejeune.fr/framework/utiliser-les-date-avec-zend_date/
this is i did it :
Zend_Date::now->toString('dd-MM-yyyy HH:mm:ss')
output from this format is "24-03-2012 13:02:01"
and you can modified your date format
I've always use $date->__toString('YYYY-MM-dd HH-mm-ss'); method in the past but today didn't work. I was getting the default output of 'Nov 1, 2013 12:19:23 PM'
So today I used $date->get('YYYY-MM-dd HH-mm-ss'); as mentioned above. Seems to have solved my problem.
You can find more information on this on output formats here: http://framework.zend.com/manual/1.12/en/zend.date.constants.html