tags:

views:

43

answers:

3

Hi, I'm retrieving a date from a MySQL database that shows up like this: '2010-03-09 09:11:30'

How can I change the date to '2010-03-09 00:00:00'? I'm using PHP to perform the query. Thanks!

+1  A: 

Are you sure it is '2010-3-9 09:11:30' and not '2010-03-09 09:11:30'? If you really are getting the first from the DB, fix your schema fast.

Anyway...

A kind-of-ugly solution is:

$startOfDay = (substr('2010-3-9 09:11:30', 0, -8) . '00:00:00');

Coronatus
Oops, sorry that was a typo. I'm REALLY tired. How would I do this for any given date?
If the timestamps all follow that format, this should work for any date.
Coronatus
Thanks, I will definitely keep this handy for the near future. I am going with deceze's solution right now because it works better with a loop I'm doing.
+1  A: 
$time = '2010-03-09 09:11:30';
$timestamp = strtotime($time);
$zeroedtimestamp = mktime(0, 0, 0, date('n', $timestamp), date('j', $timestamp), date('Y', $timestamp));
echo date('Y-m-d H:i:s', $zeroedtimestamp);
deceze
Just tested it and it works! Thank you so much!
Notice that Coronatus' solution is both shorter and faster and should work fine if all dates are in the same format. The above code is "doing it properly" though. :)
deceze
@deceze - I would have "done it properly" but I can never remember the order of mktime()'s parameters. :D
Coronatus
@Coronatus Neither can I, that's why you have a shortcut to the PHP docs search function on your machine! ;)
deceze
why bother to do all these transformations?
Col. Shrapnel
@Col. Because if you want the actual timestamp, that's what you gotta do. You rarely need just the string.
deceze
So, who need the actual timestamp here? To whom you answer?
Col. Shrapnel
`strtotime(strtok(" ",$date).'00:00:00');` would be shorter anyway. it it happen to you to have a timestamp
Col. Shrapnel
Well Col., the asker needs it... obviously...
Coronatus
@Col. Sometimes it helps to not take requests 100% literally.
deceze
@Coronatus you messed up with `timestamp` meanings probably. deceze is talking of unix timestamp I believe. And his method is just ugly
Col. Shrapnel
@Col. Thanks. If you want to produce a zeroed timestamp (yes, UNIX), this is probably the most robust method to do it. If you're just interested in the output and don't care about the timestamp, there are indeed easier methods. There's too little context to know what the OP wants exactly, but I figured he'd know how to `substr` a simple string by himself. Juggling timestamps is what trips most people up though, so that's what my answer was aimed at.
deceze
Ahaha, all in vain :)
Col. Shrapnel
+1  A: 
echo strtok(" ",$date).'00:00:00';

Why not to learn strings operations a bit? I's basic PHP knowledge as it's HTML text preprocessor. Most PHP operations is string parsing. It' really worth to learn some string functions

Col. Shrapnel