• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

taobig / php-helper / 10332570694

10 Aug 2024 03:14PM UTC coverage: 94.961% (-0.1%) from 95.108%
10332570694

push

github

taobig
Update DatetimeHelper::convertTimezone()

5 of 6 new or added lines in 1 file covered. (83.33%)

490 of 516 relevant lines covered (94.96%)

1.52 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.18
/src/DatetimeHelper.php
1
<?php
2

3
namespace taobig\helpers;
4

5
use DateTime;
6
use DateTimeZone;
7
use taobig\helpers\exception\RuntimeException;
8

9
/**
10
 * Class DatetimeHelper
11
 * @package taobig\helpers
12
 *
13
 * //Timestamp => DateTime string/DateTime Object
14
 * $str = date('Y-m-d H:i:s.u', time());
15
 * $obj = (new DateTime())->setTimestamp(time());
16
 *
17
 * $dt = new \DateTime();
18
 * $dt->setTimestamp(0);
19
 *
20
 * //DateTime string ==> Timestamp/DateTime Object
21
 * $timestamp = strtotime(date('Y-m-d H:i:s'));// to Timestamp
22
 * $obj = new \DateTime($str);//to DateTime Object
23
 *
24
 * //DateTime Object ==> DateTime string/Timestamp
25
 * $str = (new \DateTime($str))->format('Y-m-d H:i:s.u');
26
 * $timestamp = (new \DateTime($str))->getTimestamp();
27
 *
28
 *
29
 * //DateInterval
30
 * $date = new \DateTime(date("Y-m-d"));
31
 * $date->sub(new \DateInterval('P1D'));
32
 * $yesterday = $date->format('Y-m-d');
33
 *
34
 * $date = new \DateTime("2021-04-20");
35
 * $date->sub(new \DateInterval('P1DT1H1M1S'));
36
 * echo $date->format('Y-m-d H:i:s');// 2021-04-18 22:58:59
37
 *
38
 * $date = new \DateTime("2021-04-20");
39
 * $date->add(new \DateInterval('P1DT1H1M1S'));
40
 * echo $date->format('Y-m-d H:i:s');// 2021-04-21 01:01:01
41
 *
42
 * $date = new \DateTime("2021-04-20");
43
 * $date->add(new \DateInterval('P1Y1M1DT1H1M1S'));
44
 * echo $date->format('Y-m-d H:i:s');// 2022-05-21 01:01:01
45
 */
46
class DatetimeHelper
47
{
48

49
    /**
50
     * this method need 64-bit PHP runtime.
51
     * @return int
52
     * @throws RuntimeException
53
     */
54
    public static function millisecondTimestamp(): int
55
    {
56
        if (PHP_INT_SIZE < 8) {
1✔
57
            throw new RuntimeException("Cannot be executed on 32-bit PHP...");
×
58
        }
59
        $mt = explode(' ', microtime());
1✔
60
        return ((int)$mt[1]) * 1000 + ((int)round($mt[0] * 1000));
1✔
61
    }
62

63
    public static function getDatetime(): string
64
    {
65
        return date("Y-m-d H:i:s");
1✔
66
    }
67

68
    public static function getDate(): string
69
    {
70
        return date('Y-m-d');
1✔
71
    }
72

73
    /**
74
     * @param int|string|DateTime|null $referenceTime time() or "2019-07-31" or DateTime
75
     * @return false|string
76
     */
77
    public static function getYesterdayDate($referenceTime = null)
78
    {
79
        $time = time();
1✔
80
        if (is_int($referenceTime)) {
1✔
81
            $time = $referenceTime;
1✔
82
        } else if (is_string($referenceTime)) {
1✔
83
            $time = strtotime($referenceTime);
1✔
84
        } else if ($referenceTime instanceof DateTime) {
1✔
85
            $time = $referenceTime->getTimestamp();
1✔
86
        }
87
        return date("Y-m-d", strtotime("-1 days", $time));
1✔
88
    }
89

90
    /**
91
     * @param int|string|DateTime|null $referenceTime time() or "2019-07-31" or DateTime
92
     * @return false|string
93
     */
94
    public static function getTomorrowDate($referenceTime = null)
95
    {
96
        $time = time();
1✔
97
        if (is_int($referenceTime)) {
1✔
98
            $time = $referenceTime;
1✔
99
        } else if (is_string($referenceTime)) {
1✔
100
            $time = strtotime($referenceTime);
1✔
101
        } else if ($referenceTime instanceof DateTime) {
1✔
102
            $time = $referenceTime->getTimestamp();
1✔
103
        }
104
        return date("Y-m-d", strtotime("+1 days", $time));
1✔
105
    }
106

107
    /**
108
     * this method need 64-bit PHP runtime.(32-bit时只能表示67年的时间差)
109
     * @param string $strDtLeft
110
     * @param string $strDtRight
111
     * @return int
112
     * @throws \Exception
113
     */
114
    public static function datetimeDiff(string $strDtLeft, string $strDtRight): int
115
    {
116
        $dtLeft = new DateTime($strDtLeft);
1✔
117
        $dtRight = new DateTime($strDtRight);
1✔
118

119
        return $dtLeft->getTimestamp() - $dtRight->getTimestamp();
1✔
120
    }
121

122
    /**
123
     * @param int $timestamp
124
     * @return DateTime
125
     * @throws \Exception
126
     */
127
    public static function convertTimestampToDatetime(int $timestamp): DateTime
128
    {
129
        return (new DateTime())->setTimestamp($timestamp);
1✔
130
    }
131

132
    /**
133
     * @param string $datetime
134
     * @param DateTimeZone|null $timezone
135
     * @return DateTime
136
     * @throws \Exception
137
     */
138
    public static function convertStringToDatetime(string $datetime, ?DateTimeZone $timezone = null): DateTime
139
    {
140
        return new DateTime($datetime, $timezone);
1✔
141
    }
142

143
    /**
144
     * @param string $dt '2020-03-18 00:00:00'
145
     * @param string $targetTimezone eg:'UTC','Asia/Shanghai'...
146
     * @param string|null $sourceTimezone eg:'Asia/Shanghai'..., If $timezone is omitted, the current timezone will be used
147
     * @return DateTime
148
     * @throws \Exception
149
     * @throws \DateInvalidTimeZoneException
150
     */
151
    public static function convertTimezone(string $dt, string $targetTimezone, string $sourceTimezone = null): DateTime
152
    {
153
        $sourceDateTimeZone = null;
3✔
154
        if ($sourceTimezone !== null) {
3✔
155
            if (PHP_VERSION_ID < 80300) { // DateTimeZone::__construct(string $timezone): This method throws DateInvalidTimeZoneException if the timezone supplied is not recognised as a valid timezone. Prior to PHP 8.3, this was an Exception instead.
3✔
156
                try {
157
                    $sourceDateTimeZone = new DateTimeZone($sourceTimezone);
3✔
158
                } catch (\Exception $e) {
1✔
159
                    throw new \DateInvalidTimeZoneException("DateTimeZone::__construct(): Unknown or bad timezone ()");
3✔
160
                }
161
            } else {
162
                $sourceDateTimeZone = new DateTimeZone($sourceTimezone);
×
163
            }
164
        }
165

166
        if (PHP_VERSION_ID < 80300) { // DateTimeZone::__construct(string $timezone): This method throws DateInvalidTimeZoneException if the timezone supplied is not recognised as a valid timezone. Prior to PHP 8.3, this was an Exception instead.
2✔
167
            try {
168
                $targetDateTimeZone = new DateTimeZone($targetTimezone);
2✔
169
            } catch (\Exception $e) {
1✔
170
                throw new \DateInvalidTimeZoneException("DateTimeZone::__construct(): Unknown or bad timezone ()");
2✔
171
            }
172
        } else {
NEW
173
            $targetDateTimeZone = new DateTimeZone($targetTimezone);
×
174
        }
175

176
        $targetDatetime = new DateTime($dt, $sourceDateTimeZone);
1✔
177
        $targetDatetime->setTimezone($targetDateTimeZone);
1✔
178
        return $targetDatetime;
1✔
179
    }
180

181
    /**
182
     * @param string $time String representing the time.
183
     * @param string $format Format accepted by date().
184
     * @return bool
185
     */
186
    public static function validate(string $time, string $format = 'Y-m-d'): bool
187
    {
188
        $dt = DateTime::createFromFormat($format, $time);
1✔
189
        return $dt && $dt->format($format) === $time;
1✔
190
    }
191

192
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc