Difference between revisions of "How to use JDate"

From Joomla! Documentation

m (Typo toSQL statt toUnix)
(Replaced deprecated 'source' tags with 'syntaxhighlight' tags. Other markup changes.)
 
Line 3: Line 3:
 
<translate>
 
<translate>
 
== Introduction == <!--T:1-->
 
== Introduction == <!--T:1-->
Joomla's Date class is a helper class, extended from PHP's DateTime class, which allows developers to handle date formatting more efficiently. The class allows developers to format dates for readable strings, MySQL interaction, UNIX timestamp calculation, and also provides helper methods for working in different timezones.
+
Joomla's Date class is a helper class, extended from PHP's DateTime class, which allows developers to handle date formatting more efficiently. The class allows developers to format dates for readable strings, MySQL interaction, UNIX timestamp calculation, and also provides helper methods for working in different time zones.
 
</translate>
 
</translate>
  
 
<translate>
 
<translate>
 
<!--T:21-->
 
<!--T:21-->
'''Regarding the "JDate" class name:''' This page has been updated to utilise namespaced class names. `JDate`, `JApplication` and other similarly named classes you will see throughout the Joomla documentation are actually class aliases, maintained for legacy reasons. It is recommended to use namespaced access to Joomla classes, which will improve your development experience by providing better code hints and checks in your editor, leading to fewer errors.  
+
===Regarding the ''JDate'' Class Name===
 +
This page has been updated to utilise namespaced class names. ''JDate'', ''JApplication'' and other similarly-named classes you will see throughout the Joomla documentation are actually class aliases, maintained for legacy reasons. It is recommended to use namespaced access to Joomla classes, which will improve your development experience by providing better code hints and checks in your editor, leading to fewer errors.  
  
 
<!--T:22-->
 
<!--T:22-->
You can view the full list of aliased classes [https://github.com/joomla/joomla-cms/blob/staging/libraries/classmap.php in this file inside the Joomla codebase].
+
You can view the full list of aliased classes [https://github.com/joomla/joomla-cms/blob/3.10-dev/libraries/classmap.php in this file inside the Joomla code base].
 
</translate>
 
</translate>
  
Line 19: Line 20:
 
</translate>
 
</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
use Joomla\CMS\Date\Date;
 
use Joomla\CMS\Date\Date;
  
 
$date = new Date(); // Creates a new Date object equal to the current time.
 
$date = new Date(); // Creates a new Date object equal to the current time.
</source>
+
</syntaxhighlight>
  
 
<translate>
 
<translate>
Line 30: Line 31:
 
</translate>
 
</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
use Joomla\CMS\Date\Date;
 
use Joomla\CMS\Date\Date;
  
 
$date = Date::getInstance(); // Alias of 'new Date();'
 
$date = Date::getInstance(); // Alias of 'new Date();'
</source>
+
</syntaxhighlight>
  
 
<translate>
 
<translate>
Line 43: Line 44:
 
Alternatively, you may also retrieve the current date (as a Date object) from the Application object, by using:
 
Alternatively, you may also retrieve the current date (as a Date object) from the Application object, by using:
 
</translate>
 
</translate>
<source lang="php">
+
<syntaxhighlight lang="php">
 
use Joomla\CMS\Factory;
 
use Joomla\CMS\Factory;
  
 
$date = Factory::getDate();
 
$date = Factory::getDate();
</source>
+
</syntaxhighlight>
  
 
<translate>
 
<translate>
Line 53: Line 54:
  
 
<!--T:8-->
 
<!--T:8-->
The Date constructor (and getInstance static method) accepts two optional parameters: A date string to format, and a timezone. Not passing a date string will create a Date object with the current date and time, while not passing a timezone will allow the Date object to use the default timezone set.
+
The Date constructor (and ''getInstance'' static method) accepts two optional parameters: A date string to format and a timezone. Not passing a date string will create a Date object with the current date and time, while not passing a timezone will allow the Date object to use the default timezone set.
 
</translate>
 
</translate>
  
 
<translate>
 
<translate>
 
<!--T:9-->
 
<!--T:9-->
The first argument, if used, should be a string that can be parsed using PHP's native DateTime constructor. E.g:
+
The first argument, if used, should be a string that can be parsed using PHP's native DateTime constructor. For example:
 
</translate>
 
</translate>
<source lang="php">
+
<syntaxhighlight lang="php">
 
use Joomla\CMS\Date\Date;
 
use Joomla\CMS\Date\Date;
  
Line 73: Line 74:
  
 
$date = new Date('2012-12-1 15:20:00'); // 3:20 PM, December 1st, 2012
 
$date = new Date('2012-12-1 15:20:00'); // 3:20 PM, December 1st, 2012
</source>
+
</syntaxhighlight>
  
 
<translate>
 
<translate>
Line 84: Line 85:
  
 
<!--T:24-->
 
<!--T:24-->
One note of caution when outputting Date objects in a user context: do not simply print them to the screen. The Date object's toString() method simply calls its parent's format() method, without consideration for timezones or localized date formatting. This will not result in a good user experience, and will lead to inconsistencies between the formatting in your extension, and elsewhere in Joomla. Instead, you should always output Dates using the methods shown below.</translate>
+
One note of caution when outputting Date objects in a user context: do not simply print them to the screen. The Date object's toString() method simply calls its parent's format() method, without consideration for time zones or localized date formatting. This will not result in a good user experience, and will lead to inconsistencies between the formatting in your extension, and elsewhere in Joomla. Instead, you should always output Dates using the methods shown below.</translate>
  
 
<translate>
 
<translate>
Line 90: Line 91:
  
 
<!--T:26-->
 
<!--T:26-->
A number of date formats are predefined in Joomla as part of the base language packs. This is beneficial because it means date formats can be easily internationalised. A sample of the available format strings is below, from the en-GB language pack. It is highly recommended to utilise these formatting strings when outputting dates, so that your dates will be automatically re-formatted according to a user's locale. They can be retrieved in the same way as any language string (see below for examples).
+
A number of date formats are predefined in Joomla as part of the base language packs. This is beneficial because it means date formats can be easily internationalised. A sample of the available format strings is below, from the en-GB language pack. It is highly recommended to utilise these formatting strings when outputting dates, so that your dates will be automatically re-formatted according to a user's locale. They can be retrieved in the same way as any language string. (See below for examples.)
 
</translate>
 
</translate>
  
<source lang="ini">
+
<syntaxhighlight lang="ini">
 
DATE_FORMAT_LC="l, d F Y"
 
DATE_FORMAT_LC="l, d F Y"
 
DATE_FORMAT_LC1="l, d F Y"
 
DATE_FORMAT_LC1="l, d F Y"
Line 106: Line 107:
 
DATE_FORMAT_FILTER_DATE="Y-m-d"
 
DATE_FORMAT_FILTER_DATE="Y-m-d"
 
DATE_FORMAT_FILTER_DATETIME="Y-m-d H:i:s"
 
DATE_FORMAT_FILTER_DATETIME="Y-m-d H:i:s"
</source>
+
</syntaxhighlight>
  
 
<translate>
 
<translate>
Line 112: Line 113:
  
 
<!--T:28-->
 
<!--T:28-->
As with many common output items, the HtmlHelper class is here to...help! HtmlHelper's date() method will take any date-time string that the Date constructor would accept, along with a formatting string, and output the date appropriately for the current user's timezone settings. As such, this is the recommended method for outputting dates for the user.
+
As with many common output items, the HtmlHelper class is here to... help! HtmlHelper's date() method will take any date-time string that the Date constructor would accept, along with a formatting string, and output the date appropriate for the current user's timezone settings. As such, this is the recommended method for outputting dates for the user.
 
</translate>
 
</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
use Joomla\CMS\HTML\HTMLHelper;
 
use Joomla\CMS\HTML\HTMLHelper;
 
use Joomla\CMS\Language\Text;
 
use Joomla\CMS\Language\Text;
Line 121: Line 122:
 
$myDateString = '2012-12-1 15:20:00';
 
$myDateString = '2012-12-1 15:20:00';
 
echo HtmlHelper::date($myDateString, Text::_('DATE_FORMAT_FILTER_DATETIME'));
 
echo HtmlHelper::date($myDateString, Text::_('DATE_FORMAT_FILTER_DATETIME'));
</source>
+
</syntaxhighlight>
  
 
<translate>
 
<translate>
Line 130: Line 131:
 
</translate>
 
</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
use Joomla\CMS\Language\Text;
 
use Joomla\CMS\Language\Text;
 
use Joomla\CMS\Date\Date;
 
use Joomla\CMS\Date\Date;
Line 141: Line 142:
 
$date->setTimezone($timezone);
 
$date->setTimezone($timezone);
 
echo $date->format(Text::_('DATE_FORMAT_FILTER_DATETIME'));
 
echo $date->format(Text::_('DATE_FORMAT_FILTER_DATETIME'));
</source>
+
</syntaxhighlight>
  
 
<translate>
 
<translate>
Line 158: Line 159:
 
</translate>
 
</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
use Joomla\CMS\Factory;
 
use Joomla\CMS\Factory;
 
use Joomla\CMS\HTML\HTMLHelper;
 
use Joomla\CMS\HTML\HTMLHelper;
Line 168: Line 169:
 
$timezone = Factory::getUser()->getTimezone();
 
$timezone = Factory::getUser()->getTimezone();
 
echo Factory::getDate()->setTimezone($timezone)->format(Text::_('DATE_FORMAT_FILTER_DATETIME'));
 
echo Factory::getDate()->setTimezone($timezone)->format(Text::_('DATE_FORMAT_FILTER_DATETIME'));
</source>
+
</syntaxhighlight>
  
 
<translate>
 
<translate>
Line 174: Line 175:
  
 
<!--T:34-->
 
<!--T:34-->
Because the Joomla Date object extends the PHP DateTime object, it provides methods for adding and subtracting from dates. The easiest of these methods to use is the modify() method, which accepts any relative modification string that the PHP [https://www.php.net/manual/en/function.strtotime.php strtotime]() method would accept. For example:
+
Because the Joomla Date object extends the PHP DateTime object, it provides methods for adding and subtracting from dates. The easiest of these methods to use is the modify() method, which accepts any relative modification string that the PHP [https://www.php.net/manual/en/function.strtotime.php strtotime()] method would accept. For example:
 
</translate>
 
</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
use Joomla\CMS\Date\Date;
 
use Joomla\CMS\Date\Date;
  
Line 183: Line 184:
 
$date->modify('+1 year');
 
$date->modify('+1 year');
 
echo $date->toSQL(); // 2013-12-01 15:20:00
 
echo $date->toSQL(); // 2013-12-01 15:20:00
</source>
+
</syntaxhighlight>
  
 
<translate>
 
<translate>
Line 190: Line 191:
 
</translate>
 
</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
use Joomla\CMS\Date\Date;
 
use Joomla\CMS\Date\Date;
  
Line 202: Line 203:
 
$date2->sub($interval);
 
$date2->sub($interval);
 
echo $date2->toSQL(); // 2011-11-30 15:20:00
 
echo $date2->toSQL(); // 2011-11-30 15:20:00
</source>
+
</syntaxhighlight>
  
 
<translate>
 
<translate>
Line 208: Line 209:
 
</translate>
 
</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
$date = new Date('2012-12-1 15:20:00');
 
$date = new Date('2012-12-1 15:20:00');
 
$date->toISO8601(); // 20121201T152000Z
 
$date->toISO8601(); // 20121201T152000Z
</source>
+
</syntaxhighlight>
  
 
<translate>
 
<translate>
Line 217: Line 218:
 
</translate>
 
</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
$date = new Date('2012-12-1 15:20:00');
 
$date = new Date('2012-12-1 15:20:00');
 
$date->toRFC822(); // Sat, 01 Dec 2012 15:20:00 +0000
 
$date->toRFC822(); // Sat, 01 Dec 2012 15:20:00 +0000
</source>
+
</syntaxhighlight>
  
 
<translate>
 
<translate>
Line 226: Line 227:
 
</translate>
 
</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
$date = new Date('20121201T152000Z');
 
$date = new Date('20121201T152000Z');
 
$date->toSQL(); // 2012-12-01 15:20:00
 
$date->toSQL(); // 2012-12-01 15:20:00
</source>
+
</syntaxhighlight>
  
 
<translate>
 
<translate>
Line 238: Line 239:
 
</translate>
 
</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
$date = new Date('20121201T152000Z');
 
$date = new Date('20121201T152000Z');
 
$date->toUnix(); // 1354375200
 
$date->toUnix(); // 1354375200
</source>
+
</syntaxhighlight>
  
 
<translate>
 
<translate>

Latest revision as of 15:08, 9 July 2023

Other languages:
Deutsch • ‎English • ‎Nederlands • ‎español • ‎français • ‎русский • ‎中文(台灣)‎

Introduction[edit]

Joomla's Date class is a helper class, extended from PHP's DateTime class, which allows developers to handle date formatting more efficiently. The class allows developers to format dates for readable strings, MySQL interaction, UNIX timestamp calculation, and also provides helper methods for working in different time zones.

Regarding the JDate Class Name[edit]

This page has been updated to utilise namespaced class names. JDate, JApplication and other similarly-named classes you will see throughout the Joomla documentation are actually class aliases, maintained for legacy reasons. It is recommended to use namespaced access to Joomla classes, which will improve your development experience by providing better code hints and checks in your editor, leading to fewer errors.

You can view the full list of aliased classes in this file inside the Joomla code base.

Creating a Date Instance[edit]

All of the date helper methods require an instance of the Date class. To begin, you must create one. A Date object may be created in two ways. One is the typical native method of simply creating a new instance:

use Joomla\CMS\Date\Date;

$date = new Date(); // Creates a new Date object equal to the current time.

You may also create an instance using the static method defined in Date:

use Joomla\CMS\Date\Date;

$date = Date::getInstance(); // Alias of 'new Date();'

There is no difference between these methods, as Date::getInstance simply creates a new instance of Date exactly like the first method shown.

Alternatively, you may also retrieve the current date (as a Date object) from the Application object, by using:

use Joomla\CMS\Factory;

$date = Factory::getDate();

Arguments[edit]

The Date constructor (and getInstance static method) accepts two optional parameters: A date string to format and a timezone. Not passing a date string will create a Date object with the current date and time, while not passing a timezone will allow the Date object to use the default timezone set.

The first argument, if used, should be a string that can be parsed using PHP's native DateTime constructor. For example:

use Joomla\CMS\Date\Date;

$currentTime = new Date('now'); // Current date and time
$tomorrowTime = new Date('now +1 day'); // Current date and time, + 1 day.
$plus1MonthTime = new Date('now +1 month'); // Current date and time, + 1 month.
$plus1YearTime = new Date('now +1 year'); // Current date and time, + 1 year.
$plus1YearAnd1MonthTime = new Date('now +1 year +1 month'); // Current date and time, + 1 year and 1 month.
$plusTimeToTime = new Date('now +1 hour +30 minutes +3 seconds'); // Current date and time, + 1 hour, 30 minutes and 3 seconds
$plusTimeToTime = new Date('now -1 hour +30 minutes +3 seconds'); // Current date and time, + 1 hour, 30 minutes and 3 seconds
$combinedTimeToTime = new Date('now -1 hour -30 minutes 23 seconds'); // Current date and time, - 1 hour, +30 minutes and +23 seconds

$date = new Date('2012-12-1 15:20:00'); // 3:20 PM, December 1st, 2012

A Unix timestamp (in seconds) can also be passed as the first argument, in which case it will be internally uplifted into a date. If a timezone has been specified as the second argument to the constructor, it will be converted to that timezone.

Outputting Dates[edit]

One note of caution when outputting Date objects in a user context: do not simply print them to the screen. The Date object's toString() method simply calls its parent's format() method, without consideration for time zones or localized date formatting. This will not result in a good user experience, and will lead to inconsistencies between the formatting in your extension, and elsewhere in Joomla. Instead, you should always output Dates using the methods shown below.

Common Date Formats[edit]

A number of date formats are predefined in Joomla as part of the base language packs. This is beneficial because it means date formats can be easily internationalised. A sample of the available format strings is below, from the en-GB language pack. It is highly recommended to utilise these formatting strings when outputting dates, so that your dates will be automatically re-formatted according to a user's locale. They can be retrieved in the same way as any language string. (See below for examples.)

DATE_FORMAT_LC="l, d F Y"
DATE_FORMAT_LC1="l, d F Y"
DATE_FORMAT_LC2="l, d F Y H:i"
DATE_FORMAT_LC3="d F Y"
DATE_FORMAT_LC4="Y-m-d"
DATE_FORMAT_LC5="Y-m-d H:i"
DATE_FORMAT_LC6="Y-m-d H:i:s"
DATE_FORMAT_JS1="y-m-d"
DATE_FORMAT_CALENDAR_DATE="%Y-%m-%d"
DATE_FORMAT_CALENDAR_DATETIME="%Y-%m-%d %H:%M:%S"
DATE_FORMAT_FILTER_DATE="Y-m-d"
DATE_FORMAT_FILTER_DATETIME="Y-m-d H:i:s"

The HtmlHelper Method (Recommended)[edit]

As with many common output items, the HtmlHelper class is here to... help! HtmlHelper's date() method will take any date-time string that the Date constructor would accept, along with a formatting string, and output the date appropriate for the current user's timezone settings. As such, this is the recommended method for outputting dates for the user.

use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;

$myDateString = '2012-12-1 15:20:00';
echo HtmlHelper::date($myDateString, Text::_('DATE_FORMAT_FILTER_DATETIME'));

The Date Object's format() Method[edit]

Another option is to format the Date manually. If this method is used, you will have to also manually retrieve and set the user's timezone. This method is more useful for formatting dates outside of the user interface, such as in system logs or API calls.

use Joomla\CMS\Language\Text;
use Joomla\CMS\Date\Date;
use Joomla\CMS\Factory;

$myDateString = '2012-12-1 15:20:00';
$timezone = Factory::getUser()->getTimezone();

$date = new Date($myDateString);
$date->setTimezone($timezone);
echo $date->format(Text::_('DATE_FORMAT_FILTER_DATETIME'));

Other Useful Code Examples[edit]

Quickly Outputting the Current Time[edit]

There are two easy ways of doing this.

  1. The HtmlHelper's date() method, if no date value is provided, will default to the current time.
  2. Factory::getDate() gets the current date as a Date object, which we can then format.
use Joomla\CMS\Factory;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;

// These two are functionally equivalent
echo HtmlHelper::date('now', Text::_('DATE_FORMAT_FILTER_DATETIME'));

$timezone = Factory::getUser()->getTimezone();
echo Factory::getDate()->setTimezone($timezone)->format(Text::_('DATE_FORMAT_FILTER_DATETIME'));

Adding and Subtracting from Dates[edit]

Because the Joomla Date object extends the PHP DateTime object, it provides methods for adding and subtracting from dates. The easiest of these methods to use is the modify() method, which accepts any relative modification string that the PHP strtotime() method would accept. For example:

use Joomla\CMS\Date\Date;

$date = new Date('2012-12-1 15:20:00');
$date->modify('+1 year');
echo $date->toSQL(); // 2013-12-01 15:20:00

There are also separate add() and sub() methods, for adding or subtracting time from a date object respectively. These accept PHP-standard DateInterval objects:

use Joomla\CMS\Date\Date;

$interval = new \DateInterval('P1Y1D'); // Interval represents 1 year and 1 day

$date1 = new Date('2012-12-1 15:20:00');
$date1->add($interval);
echo $date1->toSQL(); // 2013-12-02 15:20:00

$date2 = new Date('2012-12-1 15:20:00');
$date2->sub($interval);
echo $date2->toSQL(); // 2011-11-30 15:20:00

Outputting Dates in ISO 8601 Format[edit]

$date = new Date('2012-12-1 15:20:00');
$date->toISO8601(); // 20121201T152000Z

Outputting Dates in RFC 822 Format[edit]

$date = new Date('2012-12-1 15:20:00');
$date->toRFC822(); // Sat, 01 Dec 2012 15:20:00 +0000

Outputting Dates in SQL Date-Time Format[edit]

$date = new Date('20121201T152000Z');
$date->toSQL(); // 2012-12-01 15:20:00

Outputting Dates as Unix Timestamps[edit]

A Unix timestamp is expressed as the number of seconds that have passed since the Unix Epoch (the first second of Jan 1st 1970).

$date = new Date('20121201T152000Z');
$date->toUnix(); // 1354375200