Date Converter
Mi è capitato spesso di dover convertire formati di date diverse tra loro, sia per motivi di internazionalizzazione (parolona!!!), sia per motivi di controllo e/o comparazione.
PHP mette già a disposizione diversi strumenti per poter convertire date tra loro, ma uno strumento unico non c’è, e quindi il povero programmatorino deve ricorrere a diverse linee di codice o alla realizzazione di funzioni appropriate per poter portare le diverse date sullo stesso piano in termini di sintassi e valore.
Se per esempio volessi convertire una data in formato YYYY-MM-GG tipica di MySQL in formato italiano avrei 2 strade principali:
$sql_date='2011-07-23';
list($year,$month,$day)=explode('-',$qsl_date);
echo "$day/$month/$year";
oppure
date('d/m/Y',strtotime($sql_date));
Qualcuno potrebbe obbiettare: “ma il secondo esempio non ti andava bene?”
Il secondo esempio va bene solo finché il formato data è un formato riconosciuto valido dal parser della funzione strtotime, con altri formati viceversa non è possibile, e bisogna fare delle ‘pre-conversioni’ affinché si ottenga il risultato sperato.
Avvalendomi della sintassi usata in MySQL per la definizione dei modelli di date, ho quindi realizzato una piccola funzione capace di, dati 2 modelli e una variabile da verificare, convertire il formato data in maniera tale che la leggibilità del codice non venga penalizzata, e tutti i formati possano essere parsati e restituiti come ci si aspetta. No tutte le conversioni sono possibili però in quanto non si può passare per esempio alla funzione un modello che contempli solo il mese testuale e pretendere che venga restituito il timestamp.
La Sintassi
Innanzitutto facciamo riferimento a quello che c’è scritto qui in merito alle variabili utilizzate da PHP per riconoscere i componenti di una data, e che riporto per i più pigri….
The format of the outputted date string. See the formatting options below. There are also several predefined date constants that may be used instead, so for example DATE_RSS contains the format string ‘D, d M Y H:i:s’.
| format character | Description | Example returned values |
|---|---|---|
| Day | — | — |
| d | Day of the month, 2 digits with leading zeros | 01 to 31 |
| D | A textual representation of a day, three letters | Mon through Sun |
| j | Day of the month without leading zeros | 1 to 31 |
| l (lowercase ‘L’) | A full textual representation of the day of the week | Sunday through Saturday |
| N | ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) | 1 (for Monday) through 7 (for Sunday) |
| S | English ordinal suffix for the day of the month, 2 characters | st, nd, rd or th. Works well with j |
| w | Numeric representation of the day of the week | 0 (for Sunday) through 6 (for Saturday) |
| z | The day of the year (starting from 0) | 0 through 365 |
| Week | — | — |
| W | ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0) | Example: 42 (the 42nd week in the year) |
| Month | — | — |
| F | A full textual representation of a month, such as January or March | January through December |
| m | Numeric representation of a month, with leading zeros | 01 through 12 |
| M | A short textual representation of a month, three letters | Jan through Dec |
| n | Numeric representation of a month, without leading zeros | 1 through 12 |
| t | Number of days in the given month | 28 through 31 |
| Year | — | — |
| L | Whether it’s a leap year | 1 if it is a leap year, 0 otherwise. |
| o | ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0) | Examples: 1999 or 2003 |
| Y | A full numeric representation of a year, 4 digits | Examples: 1999 or 2003 |
| y | A two digit representation of a year | Examples: 99 or 03 |
| Time | — | — |
| a | Lowercase Ante meridiem and Post meridiem | am or pm |
| A | Uppercase Ante meridiem and Post meridiem | AM or PM |
| B | Swatch Internet time | 000 through 999 |
| g | 12-hour format of an hour without leading zeros | 1 through 12 |
| G | 24-hour format of an hour without leading zeros | 0 through 23 |
| h | 12-hour format of an hour with leading zeros | 01 through 12 |
| H | 24-hour format of an hour with leading zeros | 00 through 23 |
| i | Minutes with leading zeros | 00 to 59 |
| s | Seconds, with leading zeros | 00 through 59 |
| u | Microseconds (added in PHP 5.2.2) | Example: 654321 |
| Timezone | — | — |
| e | Timezone identifier (added in PHP 5.1.0) | Examples: UTC, GMT, Atlantic/Azores |
| I (capital i) | Whether or not the date is in daylight saving time | 1 if Daylight Saving Time, 0 otherwise. |
| O | Difference to Greenwich time (GMT) in hours | Example: +0200 |
| P | Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3) | Example: +02:00 |
| T | Timezone abbreviation | Examples: EST, MDT … |
| Z | Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. | -43200 through 50400 |
| Full Date/Time | — | — |
| c | ISO 8601 date (added in PHP 5) | 2004-02-12T15:19:21+00:00 |
| r | » RFC 2822 formatted date | Example: Thu, 21 Dec 2000 16:01:07 +0200 |
| U | Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) | See also time() |
A differenza della funzione nativa però noi anteporremo un simbolo % per indicare che quella è una variabile… quindi
d-m-Y
diventa
%d-%m-%Y
semplice no?
il risultato quindi vien da se… ovvero facendo uso della nostra funzione potremmo scrivere
//la data da convertire $sql_date='2011-11-23'; //il formato della data da convertire $format_in='$Y-%m-%d'; //il formato della data da restituire $format_out='%d/%m/%Y';
La funzione
Ecco quindi il codice della funzione con qualche commento…. spero sia di vostro gradimento!
function date_format_convert($from='',$to='',$date=''){
//preparo la data per trattarla
//all' interno di una regular expression
$from_reg =preg_quote($from);
//recupero i valori dal modello di input
//e creo un pattern con cui fare match sulla data
preg_match_all('/%[a-z]{1}/i',$from,$from_params);
if(empty($from_params)) $from_params[0]=array();
foreach($from_params[0] as $param){
$from_reg=str_replace($param,'(.+)',$from_reg);
}
$from_params=$from_params[0];
//chiudo il pattern con i delimitatori i e lo provo
$from_reg='#'.$from_reg.'#';
preg_match($from_reg,$date,$from_values);
array_shift($from_values);
//se non ci troviamo tra modello di input e data ritorna false
if(empty($from_values)) return false;
//se il modello è correttamente parsabile,
//possiamo provare a creare il timestamp relativo
//e convertire i valori non contemplati dal modello originale
//vale solo se trovati ALMENO anno, mese e giorno e opzionalmente
//anche ore, minuti e secondi
//questi sono anche i parametri che rappresentano la maggiorparte dei casi
//anno -- trovato se dichiarato con %Y
if(array_search('%Y',$from_params) !== false){$year_str=$from_values[array_search('%Y',$from_params)];}
//mese -- trovato se dichiarato %m oppure %n
if(array_search('%m',$from_params) !== false){$month_str=$from_values[array_search('%m',$from_params)];}
elseif(array_search('%n',$from_params) !== false){$month_str=str_pad($from_values[array_search('%n',$from_params)],2,0,STR_PAD_LEFT);}
//giorno -- trovato se dichiarato %d oppure %j
if(array_search('%d',$from_params) !== false){$day_str=$from_values[array_search('%d',$from_params)];}
elseif(array_search('%j',$from_params) !== false){$day_str=str_pad($from_values[array_search('%j',$from_params)],2,0,STR_PAD_LEFT);}
//ora -- trovato se dichiarato %H oppure %G
if(array_search('%H',$from_params) !== false){$hour_str=$from_values[array_search('%H',$from_params)];}
elseif(array_search('%G',$from_params) !== false){$hour_str=str_pad($from_values[array_search('%G',$from_params)],2,0,STR_PAD_LEFT);}
//minuti -- trovato se dichiarato %i
if(array_search('%i',$from_params) !== false){$mins_str=$from_values[array_search('%i',$from_params)];}
//secondi -- trovato se dichiarato %s
if(array_search('%s',$from_params) !== false){$secs_str=$from_values[array_search('%s',$from_params)];}
//compongo la data da parsare
$timestamp=false;
if(isset($year_str,$month_str,$day_str)){
if(isset($hour_str,$mins_str,$secs_str))
$timestamp=mktime($hour_str,$mins_str,$secs_str,$month_str,$day_str,$year_str);
else
$timestamp=mktime(0,0,0,$month_str,$day_str,$year_str);
}
//procedo alla conversione vera
//recupero i valori dal modello di output
preg_match_all('/%[a-z]{1}/i',$to,$to_params);
if(empty($to_params)) $to_params[0]=array();
foreach($to_params[0] as $tparam){
$key=array_search($tparam,$from_params);
if($key === false) $date_param = ($timestamp != false || $timestamp > 0 )?date( str_replace('%','',$tparam) ,$timestamp ):'';
else $date_param=$from_values[$key];
$to=str_replace($tparam,$date_param,$to);
}
//ritorno la data rimpiazzata e ordinata!!
return $to;
}