Ricerca…


Sintassi

  • stringa data (stringa $ formato [, int $ timestamp = time ()]))
  • int strtotime (stringa $ time [, int $ now])

Analizza le descrizioni della data inglese in un formato data

Usando la funzione strtotime() combinata con date() puoi analizzare diverse descrizioni di testo inglese in date:

// Gets the current date
echo date("m/d/Y", strtotime("now")), "\n"; // prints the current date
echo date("m/d/Y", strtotime("10 September 2000")), "\n"; // prints September 10, 2000 in the m/d/Y format
echo date("m/d/Y", strtotime("-1 day")), "\n"; // prints yesterday's date
echo date("m/d/Y", strtotime("+1 week")), "\n"; // prints the result of the current date + a week
echo date("m/d/Y", strtotime("+1 week 2 days 4 hours 2 seconds")), "\n"; // same as the last example but with extra days, hours, and seconds added to it
echo date("m/d/Y", strtotime("next Thursday")), "\n"; // prints next Thursday's date
echo date("m/d/Y", strtotime("last Monday")), "\n"; // prints last Monday's date
echo date("m/d/Y", strtotime("First day of next month")), "\n"; // prints date of first day of next month
echo date("m/d/Y", strtotime("Last day of next month")), "\n"; // prints date of last day of next month
echo date("m/d/Y", strtotime("First day of last month")), "\n"; // prints date of first day of last month
echo date("m/d/Y", strtotime("Last day of last month")), "\n"; // prints date of last day of last month

Convertire una data in un altro formato

Le basi

Il modo più semplice per convertire un formato data in un altro è usare strtotime() con date() . strtotime() convertirà la data in un timestamp Unix . Quindi Unix Timestamp può essere passato alla date() per convertirlo nel nuovo formato.

$timestamp = strtotime('2008-07-01T22:35:17.02');
$new_date_format = date('Y-m-d H:i:s', $timestamp);

O come one-liner:

$new_date_format = date('Y-m-d H:i:s', strtotime('2008-07-01T22:35:17.02'));

Tieni presente che strtotime() richiede che la data sia in un formato valido . Se non si fornisce un formato valido, verrà restituito false strtotime() restituirà false date che faranno sì che la data sia 1969-12-31.

Utilizzo di DateTime()

A partire da PHP 5.2, PHP ha offerto la classe DateTime() che ci offre strumenti più potenti per lavorare con le date (e l'ora). Possiamo riscrivere il codice precedente utilizzando DateTime() in questo modo:

$date = new DateTime('2008-07-01T22:35:17.02');
$new_date_format = $date->format('Y-m-d H:i:s');

Lavorare con timestamp Unix

date() prende un timestamp Unix come secondo parametro e restituisce una data formattata per te:

$new_date_format = date('Y-m-d H:i:s', '1234567890');

DateTime () funziona con timestamp Unix aggiungendo un @ prima del timestamp:

$date = new DateTime('@1234567890');
$new_date_format = $date->format('Y-m-d H:i:s');

Se il timestamp che hai è in millisecondi (può terminare in 000 e / o il timestamp è lungo tredici caratteri) dovrai convertirlo in secondi prima di poterlo convertire in un altro formato. Ci sono due modi per farlo:

  • Tagliare le ultime tre cifre usando substr()

Il taglio delle ultime tre cifre può essere raggiunto in diversi modi, ma l'uso di substr() è il più semplice:

$timestamp = substr('1234567899000', -3);
  • Dividere il substr per 1000

Puoi anche convertire il timestamp in secondi dividendo per 1000. Poiché il timestamp è troppo grande per i sistemi a 32 bit per fare matematica su dovrai usare la libreria BCMath per fare le matematiche come stringhe:

$timestamp = bcdiv('1234567899000', '1000');

Per ottenere un timestamp Unix puoi usare strtotime() che restituisce un timestamp Unix:

$timestamp = strtotime('1973-04-18');

Con DateTime () puoi usare DateTime::getTimestamp()

$date = new DateTime('2008-07-01T22:35:17.02');
$timestamp = $date->getTimestamp();

Se esegui PHP 5.2 puoi invece utilizzare l'opzione di formattazione U :

$date = new DateTime('2008-07-01T22:35:17.02');
$timestamp = $date->format('U');

Lavorare con formati di date non standard e ambigui

Sfortunatamente non tutte le date con le quali uno sviluppatore deve lavorare sono in un formato standard. Fortunatamente PHP 5.3 ci ha fornito una soluzione per questo. DateTime::createFromFormat() ci consente di indicare a PHP in che formato è inserita una stringa di data in modo che possa essere analizzata correttamente in un oggetto DateTime per ulteriori manipolazioni.

$date = DateTime::createFromFormat('F-d-Y h:i A', 'April-18-1973 9:48 AM');
$new_date_format = $date->format('Y-m-d H:i:s');

In PHP 5.4 abbiamo acquisito la capacità di fare l'accesso ai membri della classe in istanza, che ci ha permesso di trasformare il nostro codice DateTime() in un unico liner:

$new_date_format = (new DateTime('2008-07-01T22:35:17.02'))->format('Y-m-d H:i:s');

Purtroppo questo non funziona ancora con DateTime::createFromFormat() .

Utilizzo di costanti predefinite per il formato data

Possiamo utilizzare le costanti predefinite per il formato date() in date() invece delle convenzionali stringhe di formato data da PHP 5.1.0.


Costanti di formato di data predefinite disponibili

DATE_ATOM - Atom (2016-07-22T14: 50: 01 + 00: 00)

DATE_COOKIE - Cookie HTTP (venerdì, 22-Jul-16 14:50:01 UTC)

DATE_RSS - RSS (ven, 22 lug 2016 14:50:01 +0000)

DATE_W3C - World Wide Web Consortium (2016-07-22T14: 50: 01 + 00: 00)

DATE_ISO8601 - ISO-8601 (2016-07-22T14: 50: 01 + 0000)

DATE_RFC822 - RFC 822 (Ven, 22 Jul 16 14:50:01 +0000)

DATE_RFC850 - RFC 850 (venerdì, 22-Jul-16 14:50:01 UTC)

DATE_RFC1036 - RFC 1036 (Ven, 22 Jul 16 14:50:01 +0000)

DATE_RFC1123 - RFC 1123 (Ven, 22 Jul 2016 14:50:01 +0000)

DATE_RFC2822 - RFC 2822 (Ven, 22 Jul 2016 14:50:01 +0000)

DATE_RFC3339 - Come DATE_ATOM (2016-07-22T14: 50: 01 + 00: 00)


Esempi di utilizzo

echo date(DATE_RFC822);

Questo uscirà: Ven, 22 Jul 16 14:50:01 +0000

echo date(DATE_ATOM,mktime(0,0,0,8,15,1947));

Ciò produrrà: 1947-08-15T00: 00: 00 + 05: 30

Ottenere la differenza tra due date / orari

Il modo più fattibile è usare la classe DateTime .

Un esempio:

<?php
// Create a date time object, which has the value of ~ two years ago
$twoYearsAgo = new DateTime("2014-01-18 20:05:56");
// Create a date time object, which has the value of ~ now
$now = new DateTime("2016-07-21 02:55:07");

// Calculate the diff
$diff = $now->diff($twoYearsAgo);

// $diff->y contains the difference in years between the two dates
$yearsDiff = $diff->y;
// $diff->m contains the difference in minutes between the two dates
$monthsDiff = $diff->m;
// $diff->d contains the difference in days between the two dates
$daysDiff = $diff->d;
// $diff->h contains the difference in hours between the two dates
$hoursDiff = $diff->h;
// $diff->i contains the difference in minutes between the two dates
$minsDiff = $diff->i;
// $diff->s contains the difference in seconds between the two dates
$secondsDiff = $diff->s;

// Total Days Diff, that is the number of days between the two dates
$totalDaysDiff = $diff->days;

// Dump the diff altogether just to get some details ;)
var_dump($diff);

Inoltre, confrontare due date è molto più semplice, basta usare gli operatori di confronto , come:

<?php
// Create a date time object, which has the value of ~ two years ago
$twoYearsAgo = new DateTime("2014-01-18 20:05:56");
// Create a date time object, which has the value of ~ now
$now = new DateTime("2016-07-21 02:55:07");
var_dump($now > $twoYearsAgo); // prints bool(true)
var_dump($twoYearsAgo > $now); // prints bool(false)
var_dump($twoYearsAgo <= $twoYearsAgo); // prints bool(true)
var_dump($now == $now); // prints bool(true)


Modified text is an extract of the original Stack Overflow Documentation
Autorizzato sotto CC BY-SA 3.0
Non affiliato con Stack Overflow