Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting dates stored as varchar/rfc822

Tags:

sql

mysql

rfc822

Don't ask why (it's something out of my control), but dates are being stored as RFC-822 in our MySQL DB in varchar(125).

RFC-822 = Mon Jun 13 2011 11:30:00 GMT-0400 (EDT) or Mon Jun 13 17:00:00 EDT 2011

Is there a way I can sort by date in that format or at the very least, pull the date out as YYYYMMDD or Unix time?

like image 514
bafromca Avatar asked Jan 24 '26 17:01

bafromca


1 Answers

Some voodoo can help with the first format:

SET @dt = 'Mon Jun 13 2011 11:30:00 GMT-0400 (EDT)';

SELECT    
CONVERT_TZ(
  -- Parse all, but timezone
  STR_TO_DATE(@dt, '%a %b %e %Y %H:%i:%s'),

  -- Parse timezone to '+NN:NN' format
  INSERT(SUBSTRING_INDEX(SUBSTRING_INDEX(@dt, 'GMT', -1), ' ', 1), 4, 0, ':'),

  -- Our unified timezone
  '+00:00'
);

-- Result: 2011-06-13 15:30:00

CONVERT_TZ supports EDT-like abbreviations too, but not everywhere.

like image 79
Pavel Koryagin Avatar answered Jan 27 '26 09:01

Pavel Koryagin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!