Table of Contents

Request for Comments: DateTime::__toString

Introduction

The purpose behind this RFC is to introduce converting the DateTime object to a string representation. This is a commonly requested feature in bug reports (the most recent #62911). The issue has been coming to decisions based on the default pattern to use. In the initial patch, the ISO-8601 format has been used.

Syntactical Implementation

The syntactical implementation takes both procedural and OOP approaches into account. The following changes have been made:

Methods Added

string DateTime::__toString(void) void DateTime::setDefaultPattern(string $pattern) string DateTime::getDefaultPattern(void)

Functions Added

void date_default_pattern_set(DateTime $date, string $pattern) string date_default_pattern_get(DateTime $date)

Examples

OO Style

<?php
 
$date = new DateTime('2012-09-01 02:43:00');
echo $date; // Outputs 2012-09-01T02:43:00-0500
 
$date->setDefaultPattern('Y-m-d');
echo $date; // Outputs 2012-09-01
 
echo $date->getDefaultPattern(); // Outputs "Y-m-d"
?>

Procedural Style

<?php
 
$date = date_create('2012-09-01 02:43:00');
echo $date; // Outputs 2012-09-01T02:43:00-0500
 
date_default_pattern_set($date, 'Y-m-d');
echo $date; // Outputs 2012-09-01
 
echo date_default_pattern_get($date); // Outputs "Y-m-d"
?>

Patch

The patch for this can be found at https://github.com/downloads/willfitch/php-src/date-tostring.diff.

Changelog

  1. 2012-09-01 Initial RFC written and published