A
A
Alexander Shapoval2017-08-04 04:43:05
PHP
Alexander Shapoval, 2017-08-04 04:43:05

How not to waste time when changing format in DateTime?

Good morning, the problem I have is this, there is a field

<input type="datetime-local" name="deadlines" value="2017-06-01T08:30">

Save date and time in unix
$date = new \DateTime($deadlines);
$deadlines = $date->format('U')); // это сохраняю в бд

Then I output in the previous date
$date = new \DateTime('@' . $task['deadlines']); 
$task['deadlines'] = $date->format('Y-m-d\T\0G:30');

and I get three hours less than I saved ----------------- Just did the following, converted the entered date to unix, then what happened was converted back to the previous format (without adding to bd) and got a different result$task['deadlines']
$date = new \DateTime($deadlines);
echo 'Пришло: ' . $deadlines . '<br />';
if ($deadlines = $date->format('U')) {
     echo 'Конвертировали в : ' . $deadlines . '<br />';
    Task::create($message, $deadlines, $importance, $id_project);
}

In function
echo 'приняли:' . $deadlines . '<br/>';
$date = new \DateTime('@' . $deadlines);
echo 'Изменим в формат в котором будем выводить в будущем: ' . $date->format('Y-m-d\TH:i');

Result
Received: 2017-06-01T09:37
Converted to: 1496299020 The function
for saving to the database accepted: 1496299020
Let's change the format in which we will output in the future: 2017-06-01T06:37

As you can see, it's 09:37 and it turned out 06:37

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Shapoval, 2017-08-04
@sanek_os9

Solution: instead of prescribing

$date = new \DateTime();
$date->setTimestamp($deadlines);

Both options are taken from php.net/manual/ru/datetime.settimestamp.php
Only they work differently, which gave me a lot of pleasure in finding a solution to the problem.

N
Nazar Mokrinsky, 2017-08-04
@nazarpc

How much time has been spent on such questions, but the solution is simple: store dates in the database in a bigint (64-bit) field in the Unix timestamp format. And in the application, bring to the desired time zone. And no problems, regardless of the database server configuration.

K
kisaa, 2017-08-04
@kisaa

minutes always rounds up to 30, no matter how much I save, either 08:30 or 08:15 or 08:00 will always save 08:30

what is this line supposed to do?
$date->format('Y-m-d\T\0G:30');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question