Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: DATE_SUB/DATE_ADD that accounts for DST?

Tags:

mysql

dst

dateadd

This returns 1 (aka TRUE)

SELECT DATE_SUB(NOW(), INTERVAL 24*100 HOUR) = DATE_SUB(NOW(), INTERVAL 100 DAY);

100 days ago, the hour of day does not change. But due to Daylight Savings Time (US), 100 twenty-four hour periods ago is actually one hour earlier than if you counted by days. If the above statement accounted for DST, it would return 0 or FALSE.

Is there a way I can say to account for DST for a given statement or session? I would prefer not to use UNIX_TIMESTAMP since it cuts off anything past 2038.

like image 808
700 Software Avatar asked Apr 21 '11 18:04

700 Software


People also ask

What is Date_add in MySQL?

The DATE_ADD() function adds a time/date interval to a date and then returns the date.

How do I insert date in YYYY-MM-DD format in MySQL?

You can use str_to_date to convert a date string to MySQL's internal date format for inserting.

How do I get Saturday and Sunday between two dates in MySQL?

MySQL WEEKDAY() Function The WEEKDAY() function returns the weekday number for a given date. Note: 0 = Monday, 1 = Tuesday, 2 = Wednesday, 3 = Thursday, 4 = Friday, 5 = Saturday, 6 = Sunday.


2 Answers

You'll need to create a custom function, something like this.

DELIMITER $$

CREATE FUNCTION DST(ADatetime DATETIME) RETURNS DATETIME
BEGIN
  DECLARE result DATETIME;
  SET Result = ADatetime;
  IF ADatetime >= startDST AND ADateTime <= endDST THEN 
    result = DATE_SUB(ADatetime, INTERVAL 1 HOUR);
  END IF;
  RETURN result;
END $$

DELIMITER ;
like image 153
Johan Avatar answered Oct 30 '22 01:10

Johan


This is really just a matter of converting to UTC and back:

 CONVERT_TZ(DATE_SUB(CONVERT_TZ(NOW(),@@session.time_zone,'UTC'), INTERVAL 24*100 HOUR),'UTC',@@session.time_zone);

This assumes you have the timezone tables set up to use named time zones. If not, you can use '+0:00' instead of 'UTC'

like image 4
Garr Godfrey Avatar answered Oct 30 '22 00:10

Garr Godfrey