Save date and time to database using PHP and then display the local time of the user when showing on site

Hi All

I have spent ages trying to work this out but can’t seem to find anything specific to what I need to do and was hoping that you could give me some further info and point me in the right direction.

Basically I am making a suggestions section in a secure area of some new online software I am building.

I want to add the date and time that the suggestion or suggestion reply is added… in saying that I want to pull the information out and show the time as the local time for the user.

I have already set it up so the user has a time zone set such as Australia/Brisbane or Australia/Sydney so we know what time zone the user needs to see.

I need to know how I should save the time to the database… I think I need the column in the database to be datetime (is that correct?) but I am not too sure what function I should use to add the date and time… any ideas?

I am thinking that I should add the date and time as GMT however my server time is set to Brisbane, Australia… do I try and use GMT or my server time?

Then once the correct time is in the database is there a function to call it back out and adjust it to the correct time zone of the user?

Any help with this would be great… I think part of my issue is not knowing what terms to search for.

Many Thanks

mrmbarnes

The easiest way would probably be to store the Linux timestamp, i.e., the number of seconds passed since January 1st, 1970 GMT. That value doesn’t care about time zones, daylight savings, etc.

You can get it with time() and then go back to DateTime using DateTime::createFromFormat('U', $timestamp From Database);.

I did read somewhere that getting the local user timezone is not straight forward :slight_smile:

A comprehensive library which may be far more than required:

https://carbon.nesbot.com/.

Hey… thanks for that… I did see one tutorial that hinted on this but did not then tell me how to use the time zones… I will have a play with this and see if I can get that working… mrmbarnes

This was much easier than I thought… I have not added it to my system yet but this should work if anyone is looking for an answer:

date_default_timezone_set(“Australia/Sydney”);

$now=time();

echo(date(“d-m-Y G:i”,$now));

If I save the time() function the the DB and pull the result back out I will get the correct local time time the default timezone that will also be set for the user from the DB.

Thanks for the help… I thought all I would need is a little info to point me in the right direction.

mrmbarnes

1 Like