《php new datetime()》正文开始,本次阅读大概8分钟。
PHP中的DateTime类给我们提供了很多方便的操作方式。通过new DateTime()可以创建一个DateTime对象,然后我们就可以调用它提供的方法比如format()来获取特定格式的日期时间。
下面就来举一些例子来说明DateTime的使用方法。
$today = new DateTime(); echo $today->format('Y-m-d H:i:s'); // 2022-01-17 15:26:34 $nextweek = new DateTime('next week'); echo $nextweek->format('Y-m-d'); // 2022-01-24 $endofmonth = new DateTime('last day of next month'); echo $endofmonth->format('Y-m-d'); // 2022-02-28
通过new DateTime()创建的对象,我们可以在括号中指定一个日期时间字符串来获取对应日期时间的DateTime对象。我们还可以通过对象的modify()方法来对日期时间进行修改,比如将日期时间往后加上一些时间段。
$tomorrow = new DateTime('tomorrow'); $tomorrow->modify('+3 hours'); echo $tomorrow->format('Y-m-d H:i:s'); // 2022-01-18 03:27:12 $now = new DateTime(); $birthday = new DateTime('1999-08-31'); $age = $now->diff($birthday); echo $age->y; // 22
通过在new DateTime()中不传入任何参数,我们就可以创建一个DateTime对象来表示当前时间。使用modify()方法可以将当前时间加上或减去指定时间段,比如可以加上一些小时,分钟,天数或者年数。
使用diff()方法可以计算两个时间之间的时间间隔,返回一个DateInterval对象。通过DateInterval对象可以获取时间间隔的各个部分的值,比如年数,月数,天数等。
除了使用new DateTime()来创建对象之外,PHP还提供了DateTime的子类DateTimeImmutable。与DateTime不同的是,DateTimeImmutable对象一旦被创建后,就不能再进行修改。如果需要进行修改,则需要创建一个新的DateTimeImmutable对象。
$today = new DateTimeImmutable(); $tomorrow = $today->modify('+1 day'); echo $today->format('Y-m-d'); // 2022-01-17 echo $tomorrow->format('Y-m-d'); // 2022-01-18
使用DateTimeImmutable不用担心对象的修改会影响程序的其他部分。如果需要进行修改,则需要创建一个新的DateTimeImmutable对象。
在DateTime中还提供了很多有用的方法,比如setTimezone()、getTimestamp()、getOffset()等等。通过这些方法可以进行更加复杂的日期时间操作。这里就不一一列举了。
总之,通过new DateTime()创建的对象在PHP中可以进行很多方便的日期时间操作。我们可以通过format()、modify()等方法来获取和计算日期时间,从而更好地编写日期时间相关的程序。