Jump to content

MySQL DATE_FORMAT + PHP Time Comparison in Query


drath

Recommended Posts

MySQL Version: 5.0.32

 

Hello there guys, I've been stumped for awhile using DATE_FORMAT in a SELECT that I have been creating. Unfortunately the field is not in a timestamp, or a straightforward datetime format, and there is no ability to edit that, so it looks like it's DATE_FORMAT to the rescue... except it's not working (yet).

 

The field (lastlogin) is formatted as: July 24th, 2010 2:03 PM or in PHP: date('F jS, Y g:i A').

 

As far as I can tell, the MySQL equivalent of that is %M %D, %Y %l:%i %p.

 

This is my query for trying to select only the times within the last month:

 

$sql = "SELECT snip FROM snip WHERE DATE_FORMAT('lastlogin', '%M %D, %Y %l:%i %p') >= '" . date("F jS, Y g:i A", strtotime("-1 month")) . "' ORDER BY snip DESC LIMIT 20";

 

Can anybody spot what I may be doing wrong here? It is not returning any error, so I assume it is at least executing, but nothing is showing up, which means I made a formatting mistake possible? Thanks!

 

*EDIT* The PHP portion in there is confirmed working, it returns a date of the previous month in the proper format, "September 19th, 2011 6:39 PM" for example at the time of this post.

 

Link to comment
Share on other sites

Whoever set it up that way should have their testicles forcibly removed; if you can get someone to change it, you'd be much better off to do so. You cant do a greater than / less than comparison on a date in that format. You're going to need to use MySQ's STR_TO_DATE() to format the date string into a valid YYYY-MM-DD HH:MM:SS format, then use DATE_SUB() to get the value for the comparison.

Link to comment
Share on other sites

For posterity sake, here is the final query I used to get this working:

 

WHERE STR_TO_DATE(lastlogin, '%M %D, %Y %l:%i %p') >= DATE_SUB(NOW(), INTERVAL 1 MONTH)

 

I thought I used to be able to mark the thread as solved? Either way, it's SOLVED :)

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.