From 89ac72b77d0390e03663117fe1a72c7e9a748236 Mon Sep 17 00:00:00 2001 From: ghost Date: Tue, 3 Oct 2023 00:25:48 +0300 Subject: [PATCH] implement time service --- src/Service/TimeService.php | 61 +++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/Service/TimeService.php diff --git a/src/Service/TimeService.php b/src/Service/TimeService.php new file mode 100644 index 0000000..cec6b8d --- /dev/null +++ b/src/Service/TimeService.php @@ -0,0 +1,61 @@ +translator = $translator; + } + + public function ago(int $time): string + { + $diff = time() - $time; + + if ($diff < 1) + { + return self::$translator->trans('now'); + } + + $values = + [ + 365 * 24 * 60 * 60 => $this->translator->trans('year'), + 30 * 24 * 60 * 60 => $this->translator->trans('month'), + 24 * 60 * 60 => $this->translator->trans('day'), + 60 * 60 => $this->translator->trans('hour'), + 60 => $this->translator->trans('minute'), + 1 => $this->translator->trans('second') + ]; + + $plural = [ + $this->translator->trans('year') => $this->translator->trans('years'), + $this->translator->trans('month') => $this->translator->trans('months'), + $this->translator->trans('day') => $this->translator->trans('days'), + $this->translator->trans('hour') => $this->translator->trans('hours'), + $this->translator->trans('minute') => $this->translator->trans('minutes'), + $this->translator->trans('second') => $this->translator->trans('seconds') + ]; + + foreach ($values as $key => $value) + { + $result = $diff / $key; + + if ($result >= 1) + { + $round = round($result); + + return sprintf( + '%s %s %s', + $round, + $round > 1 ? $plural[$value] : $value, + $this->translator->trans('ago') + ); + } + } + } +} \ No newline at end of file