Jump to content

Round timestamp to nearest day (midnight)


Mutley

Recommended Posts

I have a date formatted like this:

 

Year-Month-Day

2009-03-08

 

When I convert it to timestamp (using strtotime) I want it to round it to that days midnight. It gets the day/month/year correct but adds a random hour (which I don't understand as I've not specified an hour for the timestamp).

 

Any ideas?

 

Thanks in Advance,

Nick.

 

Link to comment
Share on other sites

by "converting to timestamp" i am guessing you mean using the value in a mysql database??  if so, the raw date format for mysql is yyyymmddhhmmss, which means that if you are loading a datetime/timestamp field into a database, convert the field to..

 

20070307000000

 

before the insert...to round the date the easiest way to do that is to add 12 hours to the current time (military time), and if over 24 then add a day to your date field.

 

hope this helps

- mark

Link to comment
Share on other sites

It gets the day/month/year correct but adds a random hour (which I don't understand as I've not specified an hour for the timestamp).

 

What makes you think so?

 

<?php
echo date("Y-d-m H:i:s",strtotime("2009-03-08"));
?>

 

echoes: 2009-08-03 00:00:00

Link to comment
Share on other sites

strtotime() produces a Unix timestamp that corresponds to the date/time it is supplied with in the current time zone. date() converts the timestamp it is supplied with back to a date/time in the current time zone. Each different time zone will give a different Unix Timestamp for the same supplied date/time. These conversions into/out of a Unix timestamp also produce unexpected values due to DST changes and if your DST database is not up to date with any change in DST start/stop dates.

 

What code are you using to produce the 15 Mar 2009 05:00:00 GMT value? The timestamp you get in your timezone for midnight will produce the corresponding date/time in GMT if your time zone is not GMT.

 

And what are you trying to do, because it is likely there is an easier way that will avoid the use of a Unix timestamp and the problems of converting to/from it?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.