Add the convert format support
git-svn-id: https://svn.fournier38.fr/svn/ProgSVN/trunk@3521 bf3deb0d-5f1a-0410-827f-c0cc1f45334c
This commit is contained in:
25
Tests/convertTest.php
Normal file
25
Tests/convertTest.php
Normal file
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
require_once ("convert.php");
|
||||
|
||||
/** Test the Conversion of format */
|
||||
class test_convert extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
public function test_convertDate1 ()
|
||||
{
|
||||
$res = \convert::convertDate ("2017-04-13", "Y-m-d", "d/m/Y");
|
||||
$this->assertSame ($res, "13/04/2017");
|
||||
}
|
||||
|
||||
public function test_convertDate2 ()
|
||||
{
|
||||
$this->setExpectedException ("Exception");
|
||||
$res = \convert::convertDate ("2017-13-33", "Y-m-d", "d/m/Y", true);
|
||||
}
|
||||
|
||||
public function test_convertDate3 ()
|
||||
{
|
||||
$res = \convert::convertDate ("2017-13-33", "Y-m-d", "d/m/Y");
|
||||
$this->assertSame ($res, "2017-13-33");
|
||||
}
|
||||
}
|
||||
43
convert.php
Normal file
43
convert.php
Normal file
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
/** DomFramework
|
||||
@package domframework
|
||||
@author Dominique Fournier <dominique@fournier38.fr> */
|
||||
|
||||
/** Convert a format to another one
|
||||
*/
|
||||
class convert
|
||||
{
|
||||
/** Convert Date received in one format to another.
|
||||
* If the provided string is not corresponding to the format, don't change
|
||||
* anything.
|
||||
* Format used http://php.net/manual/en/datetime.createfromformat.php
|
||||
* Do not accept the locale ! The language of the dates is always in english
|
||||
* @param string $inputDate The date to modify
|
||||
* @param string $inputFormat The input format of the date
|
||||
* @param string $outputFormat The output format of the date
|
||||
* @param bool|null $exception If set, generate an exception if the provided
|
||||
* date is invalid
|
||||
* @return string
|
||||
*/
|
||||
public static function convertDate ($inputDate, $inputFormat, $outputFormat,
|
||||
$exception = false)
|
||||
{
|
||||
$date = \DateTime::CreateFromFormat ($inputFormat, $inputDate);
|
||||
if ($date === false)
|
||||
{
|
||||
if ($exception !== false)
|
||||
throw new \Exception (
|
||||
"Invalid date provided or not matching the format", 500);
|
||||
return $inputDate;
|
||||
}
|
||||
$errors = $date->getLastErrors();
|
||||
if ($errors["warning_count"] > 0 || $errors["error_count"] > 0)
|
||||
{
|
||||
if ($exception !== false)
|
||||
throw new \Exception (
|
||||
"Invalid date provided or not matching the format", 500);
|
||||
return $inputDate;
|
||||
}
|
||||
return $date->format ($outputFormat);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user