Skip to content

Commit

Permalink
Add timezone class
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewjmead committed Jun 5, 2023
1 parent c37beae commit 01f4296
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 0 deletions.
56 changes: 56 additions & 0 deletions source/Timezone.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

namespace Proper;

use DateTimeZone;

class Timezone {
public static function utc_timezone(): DateTimeZone {
return new DateTimeZone( 'UTC' );
}

public static function utc_offset(): string {
return '+00:00';
}

public static function site_timezone(): DateTimeZone {
$timezone_string = get_option( 'timezone_string' );

if ( $timezone_string ) {
return new DateTimeZone( $timezone_string );
} else {
return new DateTimeZone( self::site_offset() );
}
}

// Will return an offset using the WordPress timezone set by the user
// Example return values: -04:00, +00:00, or +5:45
public static function site_offset(): string {
// Start with the offset such as -4, 0, or 5.75
$offset_number = (float) get_option( 'gmt_offset' );

// Build a string to represent the offset such as -04:00, +00:00, or +5:45
$result = '';

// Start with either - or +
$result .= $offset_number < 0 ? '-' : '+';

$whole_part = abs( $offset_number );
$hour_part = floor( $whole_part );
$minute_part = $whole_part - $hour_part;

$hours = strval( $hour_part );
$minutes = strval( $minute_part * 60 );

// Add hour part to result
$result .= str_pad( $hours, 2, '0', STR_PAD_LEFT );

// Add separator
$result .= ':';

// Add minute part to result
$result .= str_pad( $minutes, 2, '0', STR_PAD_LEFT );

return $result;
}
}
38 changes: 38 additions & 0 deletions tests/TimezoneTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

namespace Proper;

use DateTimeZone;

class TimezoneTest extends \WP_UnitTestCase {
protected function setUp(): void {
delete_option('timezone_string', 'America/New_York');
}

public function test_utc_timezone() {
$this->assertEquals( new DateTimeZone( 'UTC' ), Timezone::utc_timezone() );
}

public function test_utc_offset() {
$this->assertEquals( '+00:00', Timezone::utc_offset() );
}

public function test_site_timezone() {
update_option('timezone_string', 'America/New_York');
$this->assertEquals(new DateTimeZone('America/New_York'), Timezone::site_timezone());
}
public function test_site_offset() {
update_option('timezone_string', 'America/New_York');
$this->assertEquals('-04:00', Timezone::site_offset());
}

public function test_site_timezone_with_offset_timezone() {
update_option('gmt_offset', '8.75');
$this->assertEquals(new DateTimeZone('+08:45'), Timezone::site_timezone());
}

public function test_site_offset_with_offset_timezone() {
update_option('gmt_offset', '8.75');
$this->assertEquals('+08:45', Timezone::site_offset());
}
}

0 comments on commit 01f4296

Please sign in to comment.