Answer the question
In order to leave comments, you need to log in
How to correctly convert days to a date with a fixed number of days in a month?
Recently I have been training in OOP and found such a problem. I'm not sure about the correct solution, so I'm asking for help.
Good afternoon, there is a task of earth time converter. Somewhere in the universe, the planet NN dangles on which the day is 24 hours (like on earth), but there are 25 days in a month and 16 months in a year. You need to write a date converter between planet earth and planet NN. In the original, there are 5 such planets in the problem, but they differ only in the number of months in a year and the number of days in a month.
At the output, you need to get something like: Earth yyyy-mm-dd and NN: yyyy-mm-dd
It turns out that the earth day is the minimum indivisible unit (it is also a day on the planet NN)
In fact, I see here a class for the earth and a class for all other planets that will simply have their own getter and setter (to set the number of months in a year and days in a month)
There are 2 methods in the earth class
// Получаю количество дней от начала времен :)
public function getAmountDaysByDate ($date) {
$startDate = new DateTime("0001-01-01");
$currentDate = new DateTime($date);
$interval = $startDate->diff($currentDate);
return $interval->days;
}
// Получаю дату по количеству дней от начала времен
public function calculateDateByDays ($days) {
$startDate = '0001-01-01';
$date = new DateTime($startDate);
$date->add(new DateInterval('P'.$days.'D'));
$currentDate = $date->format('Y-m-d');
return $currentDate;
}
public $month = 16;
public $days = 25;
// Так как у меня большие проблемы с алгоритмами, лучше способа чем округлять дробь в меньшую сторону и отнимать от первоначального значения я не нашел... ( можно было использовать intdiv )
public function getCurrentDateByDays($days)
{
$currentYear = floor ($days / ($this->month*$this->days));
$daysMonth = $days - $currentYear*$this->month*$this->days;
$currentMonth = floor ($daysMonth/$this->days);
$currentDays = $daysMonth - $currentMonth*$this->days;
return str_pad($currentYear+1, 4, '0', STR_PAD_LEFT).'-'.str_pad($currentMonth+1, 2, '0', STR_PAD_LEFT).'-'.str_pad($currentDays+1, 2, '0', STR_PAD_LEFT);
}
// А это наверняка можно решить более красиво чем отнимать 1
public function getDaysByCurrentDate($date)
{
list($year, $month, $day) = explode("-", $date);
$days = ($year - 1) * $this->month * $this->days + ($month - 1) * $this->days + $day;
return $days;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question