La conversione alla data in PHP in formato aaaammgg
Domanda
Ho date nel seguente formato (ggmmaaaa, 18751104, 19140722)...qual è il modo più semplice per convertire la data()....o utilizza mktime() e sottostringhe la mia opzione migliore...?
Soluzione
Utilizzare strtotime()
per convertire una stringa contenente una data in una Unix timestamp:
<?php
// both lines output 813470400
echo strtotime("19951012"), "\n",
strtotime("12 October 1995");
?>
È possibile passare il risultato come secondo parametro date()
per riformattare la data da te:
<?php
// prints 1995 Oct 12
echo date("Y M d", strtotime("19951012"));
?>
Nota
strtotime()
riuscirà con le date prima di Unix epoch, all'inizio del 1970.
Come alternativa, che funziona con le date prima del 1970:
<?php
// Returns the year as an offset since 1900, negative for years before
$parts = strptime("18951012", "%Y%m%d");
$year = $parts['tm_year'] + 1900; // 1895
$day = $parts['tm_mday']; // 12
$month = $parts['tm_mon']; // 10
?>
Altri suggerimenti
Personalmente, mi basta usare substr () perché è probabilmente il modo più leggero di farlo comunque.
Ma ecco una funzione che prende una data, di cui è possibile specificare il formato. Esso restituisce un array associativo, così si potrebbe fare per esempio (non testato):
$parsed_date = date_parse_from_format('Ymd', $date);
$timestamp = mktime($parsed_date['year'], $parsed_date['month'], $parsed_date['day']);
http://uk.php.net/ manuale / it / function.date-analizzare-da-format.php
Anche se devo dire, non trovo che qualsiasi più facile o più efficace della semplice:
mktime(substr($date, 0, 4), substr($date, 4, 2), substr($date, 6, 2));
dare un'occhiata alla strptime
Bene grazie per tutte le risposte, ma il problema sembra affliggere 1900 ogni risposta che ho ricevuto. Ecco una copia della funzione che sto usando qualcuno dovrebbe essere utile per loro in futuro.
public static function nice_date($d){
$ms = array(
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
);
$the_return = '';
$the_month = abs(substr($d,4,2));
if ($the_month != 0) {
$the_return .= $ms[$the_month-1];
}
$the_day = abs(substr($d,6,2));
if ($the_day != 0){
$the_return .= ' '.$the_day;
}
$the_year = substr($d,0,4);
if ($the_year != 0){
if ($the_return != '') {
$the_return .= ', ';
}
$the_return .= $the_year;
}
return $the_return;
}
(PHP 5> = 5.3.0, PHP 7):
È possibile ottenere un'istanza di DateTime con:
$dateTime = \DateTime::createFromFormat('Ymd|', '18951012');
e convertirlo in un timestamp:
$timestamp = $dateTime->getTimestamp();
// -> -2342217600