class.json-api-date.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. class WPCOM_JSON_API_Date {
  3. /**
  4. * Returns ISO 8601 formatted datetime: 2011-12-08T01:15:36-08:00
  5. *
  6. * @param $date_gmt (string) GMT datetime string.
  7. * @param $date (string) Optional. Used to calculate the offset from GMT.
  8. *
  9. * @return string
  10. */
  11. static function format_date( $date_gmt, $date = null ) {
  12. $timestamp_gmt = strtotime( "$date_gmt+0000" );
  13. if ( null === $date ) {
  14. $timestamp = $timestamp_gmt;
  15. $hours = $minutes = $west = 0;
  16. } else {
  17. $date_time = date_create( "$date+0000" );
  18. if ( $date_time ) {
  19. $timestamp = date_format( $date_time, 'U' );
  20. } else {
  21. $timestamp = 0;
  22. }
  23. // "0000-00-00 00:00:00" == -62169984000
  24. if ( - 62169984000 == $timestamp_gmt ) {
  25. // WordPress sets post_date=now, post_date_gmt="0000-00-00 00:00:00" for all drafts
  26. // WordPress sets post_modified=now, post_modified_gmt="0000-00-00 00:00:00" for new drafts
  27. // Try to guess the correct offset from the blog's options.
  28. $timezone_string = get_option( 'timezone_string' );
  29. if ( $timezone_string && $date_time ) {
  30. $timezone = timezone_open( $timezone_string );
  31. if ( $timezone ) {
  32. $offset = $timezone->getOffset( $date_time );
  33. }
  34. } else {
  35. $offset = 3600 * get_option( 'gmt_offset' );
  36. }
  37. } else {
  38. $offset = $timestamp - $timestamp_gmt;
  39. }
  40. $west = $offset < 0;
  41. $offset = abs( $offset );
  42. $hours = (int) floor( $offset / 3600 );
  43. $offset -= $hours * 3600;
  44. $minutes = (int) floor( $offset / 60 );
  45. }
  46. return (string) gmdate( 'Y-m-d\\TH:i:s', $timestamp ) . sprintf( '%s%02d:%02d', $west ? '-' : '+', $hours, $minutes );
  47. }
  48. /**
  49. * Returns ISO 8601 formatted duration interval: P0DT1H10M0S
  50. *
  51. * @param string $time Duration in minutes or hours.
  52. *
  53. * @return null|string
  54. */
  55. static function format_duration( $time ) {
  56. $timestamp = strtotime( $time, 0 );
  57. // Bail early if we don't recognize a date.
  58. if ( empty( $timestamp ) ) {
  59. return;
  60. }
  61. $days = floor( $timestamp / 86400 );
  62. $timestamp = $timestamp % 86400;
  63. $hours = floor( $timestamp / 3600 );
  64. $timestamp = $timestamp % 3600;
  65. $minutes = floor( $timestamp / 60 );
  66. $timestamp = $timestamp % 60;
  67. return (string) sprintf(
  68. 'P%dDT%dH%dM%dS',
  69. $days,
  70. $hours,
  71. $minutes,
  72. $timestamp
  73. );
  74. }
  75. }