code_junkie

PHP DateTime microseconds always returns 0

Nov 11th, 2011
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. <?php
  2. $dt = new DateTime();
  3. echo $dt->format("Y-m-dTH:i:s.u") . "n";
  4. ?>
  5.  
  6. [root@www1 ~]$ php date_test.php
  7. 2008-10-03T20:31:26.000000
  8. [root@www1 ~]$ php date_test.php
  9. 2008-10-03T20:31:27.000000
  10. [root@www1 ~]$ php date_test.php
  11. 2008-10-03T20:31:27.000000
  12. [root@www1 ~]$ php date_test.php
  13. 2008-10-03T20:31:28.000000
  14.  
  15. function udate($format, $utimestamp = null)
  16. {
  17. if (is_null($utimestamp))
  18. $utimestamp = microtime(true);
  19.  
  20. $timestamp = floor($utimestamp);
  21. $milliseconds = round(($utimestamp - $timestamp) * 1000000);
  22.  
  23. return date(preg_replace('`(?<!\\)u`', $milliseconds, $format), $timestamp);
  24. }
  25.  
  26. echo udate('H:i:s.u'); // 19:40:56.78128
  27.  
  28. function getTimestamp()
  29. {
  30. return date("Y-m-dTH:i:s") . substr((string)microtime(), 1, 8);
  31. }
  32.  
  33. class ExtendedDateTime extends DateTime {
  34. /**
  35. * Returns new DateTime object. Adds microtime for "now" dates
  36. * @param string $sTime
  37. * @param DateTimeZone $oTimeZone
  38. */
  39. public function __construct($sTime = 'now', DateTimeZone $oTimeZone = NULL) {
  40. // check that constructor is called as current date/time
  41. if (strtotime($sTime) == time()) {
  42. $aMicrotime = explode(' ', microtime());
  43. $sTime = date('Y-m-d H:i:s.' . $aMicrotime[0] * 1000000, $aMicrotime[1]);
  44. }
  45.  
  46. // DateTime throws an Exception with a null TimeZone
  47. if ($oTimeZone instanceof DateTimeZone) {
  48. parent::__construct($sTime, $oTimeZone);
  49. } else {
  50. parent::__construct($sTime);
  51. }
  52. }
  53. }
  54.  
  55. $oDate = new ExtendedDateTime();
  56. echo $oDate->format('Y-m-d G:i:s.u');
  57.  
  58. 2010-12-01 18:12:10.146625
  59.  
  60. date_create_from_format('U.u', microtime(true))->format('Y-m-d H:i:s.u');
Add Comment
Please, Sign In to add comment