0

I have a database, which includes datetime of purchases. I would like to display it on the website 6 hours sooner that datetime in database.

(unlike) How to subtract hours from a datetime in MySQL?

I need PHP method to achive this

$dt = new DateTime($row["datetime"]);
$dt->modify('-6 hours');

Date and time is saved in $row["datetime"]. The code above doesn't work, but on many places this is stated as the proper code.

Example of what I would like to do:

Time in database: 2019-01-17 20:13:12 On website, I would like: 2019-01-17 14:13:12

Googlian
  • 6,077
  • 3
  • 38
  • 44
  • 1
    Sorry, I didn't write the code properly. The dates and times are saved as datetime in the databse. – Marko Hauptman Jan 17 '19 at 04:21
  • "The code above doesn't work" - it would be helpful if you specify what "doesn't work" means. What are you expecting to happen, and what is happening instead? – Amber Jan 17 '19 at 04:22
  • @Amber I would like to show the time, but 6 hours sooner, what happens now is that the whole table is not displayed after I changed normal $row["datetime"] to the $dt which should be 6 hours sooner. – Marko Hauptman Jan 17 '19 at 04:23
  • You have properly stored your datetime, so you can most-simply use mysql to prepare your data in your query. This is good, tidy, direct coding practice. – mickmackusa Jan 17 '19 at 04:25

1 Answers1

0

(PHP 5 >= 5.3.0, PHP 7)

You can use data_sub method to achieve this,

$date = date_create($row["datetime"]);
date_sub($date, date_interval_create_from_date_string('6 days'));
echo date_format($date, 'Y-m-d');

DateTime::sub -- date_sub — Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object

Googlian
  • 6,077
  • 3
  • 38
  • 44