Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Malaysia holiday #17

Merged
merged 19 commits into from
Oct 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 50 additions & 1 deletion src/Calendars/IslamicCalendar.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,21 @@

namespace Spatie\Holidays\Calendars;

use Carbon\CarbonImmutable;
use DateTime;
use DateTimeZone;
use IntlCalendar;
use IntlDateFormatter;
use Carbon\CarbonPeriod;
use Carbon\CarbonImmutable;
use Carbon\Exceptions\InvalidFormatException;
use Spatie\Holidays\Countries\Country;
use Spatie\Holidays\Exceptions\InvalidYear;

/** @mixin Country */
trait IslamicCalendar
{
protected string $islamicCalendarTimezone = 'UTC';

/** @return array<CarbonPeriod> */
public function eidAlFitr(int $year, int $totalDays = 3): array
{
Expand Down Expand Up @@ -138,4 +144,47 @@ protected function getOverlapping(array $collection, int $year, int $totalDays):

return null;
}

public function setIslamicCalendarTimezone(string $islamicCalendarTimezone): static
{
$this->islamicCalendarTimezone = $islamicCalendarTimezone;

return $this;
}

protected function getIslamicCalendarFormatter(): IntlDateFormatter
{
return new IntlDateFormatter(
'en_US@calendar=islamic-civil',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'UTC',
IntlDateFormatter::TRADITIONAL,
'yyyy-MM-dd'
);
}

protected function getHijriYear(int $year, bool $nextYear = false): int
{
$formatter = $this->getIslamicCalendarFormatter();
$formatter->setPattern('yyyy');
$dateTime = DateTime::createFromFormat('d/m/Y', '01/01/' . ($nextYear ? $year + 1 : $year));

if (!$dateTime) {
throw InvalidYear::invalidHijriYear();
}

return (int) $formatter->format($dateTime->getTimestamp());
}

protected function islamicToGregorianDate(string $input, int $year, bool $nextYear = false): CarbonImmutable
{
$hijriYear = $this->getHijriYear(year: $year, nextYear: $nextYear);
$formatter = $this->getIslamicCalendarFormatter();
$timestamp = (int) $formatter->parse(sprintf('%s-%s', $hijriYear, $input));

return (new CarbonImmutable())
->setTimeStamp($timestamp)
->setTimezone(new DateTimeZone($this->islamicCalendarTimezone));
}
}
Loading
Loading