Beruflich Dokumente
Kultur Dokumente
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
MySQL5.0ReferenceManual::12FunctionsandOperators::12.7DateandTimeFunctions
12.7DateandTimeFunctions
SectionNavigation[Toggle]
Thissectiondescribesthefunctionsthatcanbeusedtomanipulatetemporalvalues.SeeSection11.3,Dateand
TimeTypes,foradescriptionoftherangeofvalueseachdateandtimetypehasandthevalidformatsinwhich
valuesmaybespecified.
Table12.13Date/TimeFunctions
Name
12.6.2MathematicalFunctions
12.8WhatCalendarIsUsedByMySQL?
Description
ADDDATE()
Addtimevalues(intervals)toadatevalue
ADDTIME()
Addtime
CONVERT_TZ()
Convertfromonetimezonetoanother
CURDATE()
Returnthecurrentdate
CURRENT_DATE() ,
CURRENT_DATE
SynonymsforCURDATE()
CURRENT_TIME() ,
CURRENT_TIME
SynonymsforCURTIME()
CURRENT_TIMESTAMP() ,
CURRENT_TIMESTAMP
SynonymsforNOW()
CURTIME()
Returnthecurrenttime
DATE_ADD()
Addtimevalues(intervals)toadatevalue
DATE_FORMAT()
Formatdateasspecified
DATE_SUB()
Subtractatimevalue(interval)fromadate
DATE()
Extractthedatepartofadateordatetimeexpression
DATEDIFF()
Subtracttwodates
DAY()
SynonymforDAYOFMONTH()
DAYNAME()
Returnthenameoftheweekday
DAYOFMONTH()
Returnthedayofthemonth(031)
DAYOFWEEK()
Returntheweekdayindexoftheargument
DAYOFYEAR()
Returnthedayoftheyear(1366)
EXTRACT()
Extractpartofadate
FROM_DAYS()
Convertadaynumbertoadate
FROM_UNIXTIME()
FormatUNIXtimestampasadate
GET_FORMAT()
Returnadateformatstring
HOUR()
Extractthehour
LAST_DAY
Returnthelastdayofthemonthfortheargument
LOCALTIME() ,LOCALTIME
SynonymforNOW()
LOCALTIMESTAMP ,
LOCALTIMESTAMP()
SynonymforNOW()
MAKEDATE()
Createadatefromtheyearanddayofyear
MAKETIME()
Createtimefromhour,minute,second
MICROSECOND()
Returnthemicrosecondsfromargument
MINUTE()
Returntheminutefromtheargument
MONTH()
Returnthemonthfromthedatepassed
MONTHNAME()
Returnthenameofthemonth
NOW()
Returnthecurrentdateandtime
PERIOD_ADD()
Addaperiodtoayearmonth
PERIOD_DIFF()
Returnthenumberofmonthsbetweenperiods
QUARTER()
Returnthequarterfromadateargument
SEC_TO_TIME()
Convertssecondsto'HH:MM:SS'format
SECOND()
Returnthesecond(059)
STR_TO_DATE()
Convertastringtoadate
SUBDATE()
SynonymforDATE_SUB()wheninvokedwiththreearguments
SUBTIME()
Subtracttimes
SYSDATE()
Returnthetimeatwhichthefunctionexecutes
TIME_FORMAT()
Formatastime
TIME_TO_SEC()
Returntheargumentconvertedtoseconds
TIME()
Extractthetimeportionoftheexpressionpassed
TIMEDIFF()
Subtracttime
TIMESTAMP()
TIMESTAMPADD()
Withasingleargument,thisfunctionreturnsthedateordatetimeexpression
withtwoarguments,thesumofthearguments
Addanintervaltoadatetimeexpression
TIMESTAMPDIFF()
Subtractanintervalfromadatetimeexpression
TO_DAYS()
Returnthedateargumentconvertedtodays
UNIX_TIMESTAMP()
ReturnaUNIXtimestamp
UTC_DATE()
ReturnthecurrentUTCdate
UTC_TIME()
ReturnthecurrentUTCtime
UTC_TIMESTAMP()
ReturnthecurrentUTCdateandtime
WEEK()
Returntheweeknumber
WEEKDAY()
Returntheweekdayindex
WEEKOFYEAR()
Returnthecalendarweekofthedate(053)
YEAR()
Returntheyear
YEARWEEK()
Returntheyearandweek
12FunctionsandOperators
12.1FunctionandOperator
Reference
12.2TypeConversionin
ExpressionEvaluation
12.3Operators
12.4ControlFlowFunctions
12.5StringFunctions
12.6NumericFunctionsand
Operators
12.7DateandTimeFunctions
12.8WhatCalendarIsUsed
ByMySQL?
12.9FullTextSearch
Functions
12.10CastFunctionsand
Operators
12.11BitFunctions
12.12Encryptionand
CompressionFunctions
12.13InformationFunctions
12.14SpatialAnalysis
Functions
12.15Miscellaneous
Functions
12.16FunctionsandModifiers
forUsewithGROUPBY
Clauses
12.17PrecisionMath
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
1/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
Thequeryalsoselectsrowswithdatesthatlieinthefuture.
Functionsthatexpectdatevaluesusuallyacceptdatetimevaluesandignorethetimepart.Functionsthatexpect
timevaluesusuallyacceptdatetimevaluesandignorethedatepart.
Functionsthatreturnthecurrentdateortimeeachareevaluatedonlyonceperqueryatthestartofquery
execution.ThismeansthatmultiplereferencestoafunctionsuchasNOW()withinasinglequeryalwaysproduce
thesameresult.(Forourpurposes,asinglequeryalsoincludesacalltoastoredprogram(storedroutineor
trigger)andallsubprogramscalledbythatprogram.)ThisprinciplealsoappliestoCURDATE(),CURTIME(),
UTC_DATE(),UTC_TIME(),UTC_TIMESTAMP(),andtoanyoftheirsynonyms.
TheCURRENT_TIMESTAMP(),CURRENT_TIME(),CURRENT_DATE(),andFROM_UNIXTIME()functionsreturn
valuesintheconnection'scurrenttimezone,whichisavailableasthevalueofthetime_zonesystemvariable.In
addition,UNIX_TIMESTAMP()assumesthatitsargumentisadatetimevalueinthecurrenttimezone.See
Section10.6,MySQLServerTimeZoneSupport.
Somedatefunctionscanbeusedwithzerodatesorincompletedatessuchas'20011100',whereasothers
cannot.Functionsthatextractpartsofdatestypicallyworkwithincompletedatesandthuscanreturn0whenyou
mightotherwiseexpectanonzerovalue.Forexample:
mysql> SELECTDAYOFMONTH('20011100'),MONTH('20050000')
>0,0
OtherfunctionsexpectcompletedatesandreturnNULLforincompletedates.Theseincludefunctionsthat
performdatearithmeticorthatmappartsofdatestonames.Forexample:
mysql> SELECTDATE_ADD('20060500',INTERVAL1DAY)
>NULL
mysql> SELECTDAYNAME('20060500')
>NULL
timeexpression.
mysql> SELECTADDTIME('2007123123:59:59.999999','11:1:1.000002')
>'2008010201:01:01.000001'
mysql> SELECTADDTIME('01:00:00.999999','02:00:00.999998')
>'03:00:01.999997'
Tousenamedtimezonessuchas'MET'or'Europe/Moscow',thetimezonetablesmustbeproperlysetup.
SeeSection10.6,MySQLServerTimeZoneSupport,forinstructions.
IfyouintendtouseCONVERT_TZ()whileothertablesarelockedwithLOCKTABLES,youmustalsolockthe
mysql.time_zone_nametable.
CURDATE()
Returnsthecurrentdateasavaluein'YYYYMMDD'orYYYYMMDDformat,dependingonwhetherthefunctionis
usedinastringornumericcontext.
mysql> SELECTCURDATE()
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
2/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
>'20080613'
mysql> SELECTCURDATE()+0
>20080613
CURRENT_DATE,CURRENT_DATE()
CURRENT_DATEandCURRENT_DATE()aresynonymsforCURDATE().
CURRENT_TIME,CURRENT_TIME()
CURRENT_TIMEandCURRENT_TIME()aresynonymsforCURTIME().
CURRENT_TIMESTAMP,CURRENT_TIMESTAMP()
CURRENT_TIMESTAMPandCURRENT_TIMESTAMP()aresynonymsforNOW().
CURTIME()
Returnsthecurrenttimeasavaluein'HH:MM:SS'orHHMMSS.uuuuuuformat,dependingonwhetherthefunction
isusedinastringornumericcontext.Thevalueisexpressedinthecurrenttimezone.
mysql> SELECTCURTIME()
>'23:50:26'
mysql> SELECTCURTIME()+0
>235026.000000
DATE( expr )
Extractsthedatepartofthedateordatetimeexpression expr .
mysql> SELECTDATE('2003123101:02:03')
>'20031231'
aredateordateandtimeexpressions.Onlythedatepartsofthevaluesareusedinthecalculation.
mysql> SELECTDATEDIFF('2007123123:59:59','20071230')
>1
mysql> SELECTDATEDIFF('2010113023:59:59','20101231')
>31
DATE_ADD( date ,INTERVAL expr unit ),DATE_SUB( date ,INTERVAL expr unit )
Thesefunctionsperformdatearithmetic.The date argumentspecifiesthestartingdateordatetimevalue. expr
isanexpressionspecifyingtheintervalvaluetobeaddedorsubtractedfromthestartingdate. expr isastringit
maystartwithafornegativeintervals. unit isakeywordindicatingtheunitsinwhichtheexpressionshould
beinterpreted.
TheINTERVALkeywordandthe unit specifierarenotcasesensitive.
Thefollowingtableshowstheexpectedformofthe expr argumentforeach unit value.
unit Value
MICROSECOND
MICROSECONDS
SECOND
SECONDS
MINUTE
MINUTES
HOUR
HOURS
DAY
DAYS
WEEK
WEEKS
MONTH
MONTHS
QUARTER
QUARTERS
YEAR
YEARS
SECOND_MICROSECOND
'SECONDS.MICROSECONDS'
MINUTE_MICROSECOND
'MINUTES:SECONDS.MICROSECONDS'
MINUTE_SECOND
'MINUTES:SECONDS'
HOUR_MICROSECOND
'HOURS:MINUTES:SECONDS.MICROSECONDS'
HOUR_SECOND
'HOURS:MINUTES:SECONDS'
HOUR_MINUTE
'HOURS:MINUTES'
DAY_MICROSECOND
'DAYSHOURS:MINUTES:SECONDS.MICROSECONDS'
DAY_SECOND
'DAYSHOURS:MINUTES:SECONDS'
DAY_MINUTE
'DAYSHOURS:MINUTES'
DAY_HOUR
'DAYSHOURS'
YEAR_MONTH
'YEARSMONTHS'
Thereturnvaluedependsonthearguments:
DATETIMEifthefirstargumentisaDATETIME(orTIMESTAMP)value,orifthefirstargumentisaDATEandthe
unit valueusesHOURS,MINUTES,orSECONDS.
Stringotherwise.
ToensurethattheresultisDATETIME,youcanuseCAST()toconvertthefirstargumenttoDATETIME.
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
3/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
nosensetosubtractadateordatetimevaluefromaninterval.
mysql> SELECT'2008123123:59:59'+INTERVAL1SECOND
>'2009010100:00:00'
mysql> SELECTINTERVAL1DAY+'20081231'
>'20090101'
mysql> SELECT'20050101'INTERVAL1SECOND
>'2004123123:59:59'
mysql> SELECTDATE_ADD('2000123123:59:59',
> INTERVAL1SECOND)
>'2001010100:00:00'
mysql> SELECTDATE_ADD('2010123123:59:59',
> INTERVAL1DAY)
>'2011010123:59:59'
mysql> SELECTDATE_ADD('2100123123:59:59',
> INTERVAL'1:1'MINUTE_SECOND)
>'2101010100:01:00'
mysql> SELECTDATE_SUB('2005010100:00:00',
> INTERVAL'11:1:1'DAY_SECOND)
>'2004123022:58:59'
mysql> SELECTDATE_ADD('1900010100:00:00',
> INTERVAL'110'DAY_HOUR)
>'1899123014:00:00'
mysql> SELECTDATE_SUB('19980102',INTERVAL31DAY)
>'19971202'
mysql> SELECTDATE_ADD('1992123123:59:59.000002',
> INTERVAL'1.999999'SECOND_MICROSECOND)
>'1993010100:00:01.000001'
Ifyouspecifyanintervalvaluethatistooshort(doesnotincludealltheintervalpartsthatwouldbeexpectedfrom
the unit keyword),MySQLassumesthatyouhaveleftouttheleftmostpartsoftheintervalvalue.Forexample,if
youspecifya unit ofDAY_SECOND,thevalueof expr isexpectedtohavedays,hours,minutes,andseconds
parts.Ifyouspecifyavaluelike'1:10',MySQLassumesthatthedaysandhourspartsaremissingandthe
valuerepresentsminutesandseconds.Inotherwords,'1:10'DAY_SECONDisinterpretedinsuchawaythatitis
equivalentto'1:10'MINUTE_SECOND.ThisisanalogoustothewaythatMySQLinterpretsTIMEvaluesas
representingelapsedtimeratherthanasatimeofday.
Because expr istreatedasastring,becarefulifyouspecifyanonstringvaluewithINTERVAL.Forexample,with
anintervalspecifierofHOUR_MINUTE,6/4evaluatesto1.5000andistreatedas1hour,5000minutes:
mysql> SELECT6/4
>1.5000
mysql> SELECTDATE_ADD('20090101',INTERVAL6/4HOUR_MINUTE)
>'2009010412:20:00'
Toensureinterpretationoftheintervalvalueasyouexpect,aCAST()operationmaybeused.Totreat6/4as1
hour,5minutes,castittoaDECIMALvaluewithasinglefractionaldigit:
mysql> SELECTCAST(6/4ASDECIMAL(3,1))
>1.5
mysql> SELECTDATE_ADD('1970010112:00:00',
> INTERVALCAST(6/4ASDECIMAL(3,1))HOUR_MINUTE)
>'1970010113:05:00'
Ifyouaddtoorsubtractfromadatevaluesomethingthatcontainsatimepart,theresultisautomatically
convertedtoadatetimevalue:
mysql> SELECTDATE_ADD('20130101',INTERVAL1DAY)
>'20130102'
mysql> SELECTDATE_ADD('20130101',INTERVAL1HOUR)
>'2013010101:00:00'
IfyouaddMONTH,YEAR_MONTH,orYEARandtheresultingdatehasadaythatislargerthanthemaximumdayfor
thenewmonth,thedayisadjustedtothemaximumdaysinthenewmonth:
mysql> SELECTDATE_ADD('20090130',INTERVAL1MONTH)
>'20090228'
Datearithmeticoperationsrequirecompletedatesanddonotworkwithincompletedatessuchas'20060700'
orbadlymalformeddates:
mysql> SELECTDATE_ADD('20060700',INTERVAL1DAY)
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
4/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
>NULL
mysql> SELECT'20050332'+INTERVAL1MONTH
>NULL
Abbreviatedweekdayname(Sun ..Sat )
%b
Abbreviatedmonthname(Jan ..Dec )
%c
Month,numeric(0 ..12 )
%D
%d
Dayofthemonth,numeric(00 ..31 )
%e
Dayofthemonth,numeric(0 ..31 )
%f
Microseconds(000000 ..999999 )
%H
Hour(00 ..23 )
%h
Hour(01 ..12 )
%I
Hour(01 ..12 )
%i
Minutes,numeric(00 ..59 )
%j
Dayofyear(001 ..366 )
%k
Hour(0 ..23 )
%l
Hour(1 ..12 )
%M
Monthname(January ..December )
%m
Month,numeric(00 ..12 )
%p
AM orPM
%r
%S
Seconds(00 ..59 )
%s
Seconds(00 ..59 )
%T
Time,24hour(hh:mm:ss )
%U
%u
%V
%v
%W
Weekdayname(Sunday ..Saturday )
%w
%X
YearfortheweekwhereSundayisthefirstdayoftheweek,numeric,fourdigitsusedwith%V
%x
Yearfortheweek,whereMondayisthefirstdayoftheweek,numeric,fourdigitsusedwith%v
%Y
Year,numeric,fourdigits
%y
Year,numeric(twodigits)
%%
Aliteral% character
%x
x ,forany x notlistedabove
RangesforthemonthanddayspecifiersbeginwithzeroduetothefactthatMySQLpermitsthestoringof
incompletedatessuchas'20140000'.
AsofMySQL5.0.25,thelanguageusedfordayandmonthnamesandabbreviationsiscontrolledbythevalueof
thelc_time_namessystemvariable(Section10.7,MySQLServerLocaleSupport).
Forthe%U,%u,%V,and%vspecifiers,seethedescriptionoftheWEEK()functionforinformationaboutthemode
values.Themodeaffectshowweeknumberingoccurs.
AsofMySQL5.0.36,DATE_FORMAT()returnsastringwithacharactersetandcollationgivenby
character_set_connectionandcollation_connectionsothatitcanreturnmonthandweekdaynames
containingnonASCIIcharacters.Before5.0.36,thereturnvalueisabinarystring.
mysql> SELECTDATE_FORMAT('2009100422:23:00','%W%M%Y')
>'SundayOctober2009'
mysql> SELECTDATE_FORMAT('2007100422:23:00','%H:%i:%s')
>'22:23:00'
mysql> SELECTDATE_FORMAT('1900100422:23:00',
> '%D%y%a%d%m%b%j')
>'4th00Thu0410Oct277'
mysql> SELECTDATE_FORMAT('1997100422:23:00',
> '%H%k%I%r%T%S%w')
>'22221010:23:00PM22:23:00006'
mysql> SELECTDATE_FORMAT('19990101','%X%V')
>'199852'
mysql> SELECTDATE_FORMAT('20060600','%d')
>'00'
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
5/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
DAYNAME( date )
Returnsthenameoftheweekdayfor date .AsofMySQL5.0.25,thelanguageusedforthenameiscontrolledby
thevalueofthelc_time_namessystemvariable(Section10.7,MySQLServerLocaleSupport).
mysql> SELECTDAYNAME('20070203')
>'Saturday'
DAYOFMONTH( date )
Returnsthedayofthemonthfor date ,intherange1to31,or0fordatessuchas'00000000'or'200800
00'thathaveazerodaypart.
mysql> SELECTDAYOFMONTH('20070203')
>3
DAYOFWEEK( date )
Returnstheweekdayindexfor date (1=Sunday,2=Monday,,7=Saturday).Theseindexvaluescorrespond
totheODBCstandard.
mysql> SELECTDAYOFWEEK('20070203')
>7
DAYOFYEAR( date )
Returnsthedayoftheyearfor date ,intherange1to366.
mysql> SELECTDAYOFYEAR('20070203')
>34
FROM_DAYS( N )
Givenadaynumber N ,returnsaDATEvalue.
mysql> SELECTFROM_DAYS(730669)
>'20070703'
UseFROM_DAYS()withcautiononolddates.Itisnotintendedforusewithvaluesthatprecedetheadventofthe
Gregoriancalendar(1582).SeeSection12.8,WhatCalendarIsUsedByMySQL?.
FROM_UNIXTIME( unix_timestamp ),FROM_UNIXTIME( unix_timestamp , format )
Returnsarepresentationofthe unix_timestamp argumentasavaluein'YYYYMMDDHH:MM:SS'or
YYYYMMDDHHMMSS.uuuuuuformat,dependingonwhetherthefunctionisusedinastringornumericcontext.The
valueisexpressedinthecurrenttimezone. unix_timestamp isaninternaltimestampvaluesuchasisproduced
bytheUNIX_TIMESTAMP()function.
If format isgiven,theresultisformattedaccordingtothe format string,whichisusedthesamewayaslistedin
theentryfortheDATE_FORMAT()function.
mysql> SELECTFROM_UNIXTIME(1196440219)
>'2007113010:30:19'
mysql> SELECTFROM_UNIXTIME(1196440219)+0
>20071130103019.000000
mysql> SELECTFROM_UNIXTIME(UNIX_TIMESTAMP(),
> '%Y%D%M%h:%i:%s%x')
>'200730thNovember10:30:592007'
Note:IfyouuseUNIX_TIMESTAMP()andFROM_UNIXTIME()toconvertbetweenTIMESTAMPvaluesandUnix
timestampvalues,theconversionislossybecausethemappingisnotonetooneinbothdirections.Fordetails,
seethedescriptionoftheUNIX_TIMESTAMP()function.
GET_FORMAT({DATE|TIME|DATETIME},{'EUR'|'USA'|'JIS'|'ISO'|'INTERNAL'})
Returnsaformatstring.ThisfunctionisusefulincombinationwiththeDATE_FORMAT()andtheSTR_TO_DATE()
functions.
Thepossiblevaluesforthefirstandsecondargumentsresultinseveralpossibleformatstrings(forthespecifiers
used,seethetableintheDATE_FORMAT()functiondescription).ISOformatreferstoISO9075,notISO8601.
FunctionCall
Result
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
6/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
GET_FORMAT(DATE,'USA')
'%m.%d.%Y'
GET_FORMAT(DATE,'JIS')
'%Y%m%d'
GET_FORMAT(DATE,'ISO')
'%Y%m%d'
GET_FORMAT(DATE,'EUR')
'%d.%m.%Y'
GET_FORMAT(DATE,'INTERNAL')
'%Y%m%d'
GET_FORMAT(DATETIME,'USA')
'%Y%m%d%H.%i.%s'
GET_FORMAT(DATETIME,'JIS')
'%Y%m%d%H:%i:%s'
GET_FORMAT(DATETIME,'ISO')
'%Y%m%d%H:%i:%s'
GET_FORMAT(DATETIME,'EUR')
'%Y%m%d%H.%i.%s'
GET_FORMAT(DATETIME,'INTERNAL')
'%Y%m%d%H%i%s'
GET_FORMAT(TIME,'USA')
'%h:%i:%s%p'
GET_FORMAT(TIME,'JIS')
'%H:%i:%s'
GET_FORMAT(TIME,'ISO')
'%H:%i:%s'
GET_FORMAT(TIME,'EUR')
'%H.%i.%s'
GET_FORMAT(TIME,'INTERNAL')
'%H%i%s'
TIMESTAMPcanalsobeusedasthefirstargumenttoGET_FORMAT(),inwhichcasethefunctionreturnsthesame
valuesasforDATETIME.
mysql> SELECTDATE_FORMAT('20031003',GET_FORMAT(DATE,'EUR'))
>'03.10.2003'
mysql> SELECTSTR_TO_DATE('10.31.2003',GET_FORMAT(DATE,'USA'))
>'20031031'
HOUR( time )
Returnsthehourfor time .Therangeofthereturnvalueis0to23fortimeofdayvalues.However,therangeof
TIMEvaluesactuallyismuchlarger,soHOURcanreturnvaluesgreaterthan23.
mysql> SELECTHOUR('10:05:03')
>10
mysql> SELECTHOUR('272:59:59')
>272
LAST_DAY( date )
Takesadateordatetimevalueandreturnsthecorrespondingvalueforthelastdayofthemonth.ReturnsNULLif
theargumentisinvalid.
mysql> SELECTLAST_DAY('20030205')
>'20030228'
mysql> SELECTLAST_DAY('20040205')
>'20040229'
mysql> SELECTLAST_DAY('2004010101:01:01')
>'20040131'
mysql> SELECTLAST_DAY('20030332')
>NULL
LOCALTIME,LOCALTIME()
LOCALTIMEandLOCALTIME()aresynonymsforNOW().
LOCALTIMESTAMP,LOCALTIMESTAMP()
LOCALTIMESTAMPandLOCALTIMESTAMP()aresynonymsforNOW().
MICROSECOND( expr )
Returnsthemicrosecondsfromthetimeordatetimeexpression expr asanumberintherangefrom0to
999999.
mysql> SELECTMICROSECOND('12:00:00.123456')
>123456
mysql> SELECTMICROSECOND('2009123123:59:59.000010')
>10
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
7/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
MINUTE( time )
Returnstheminutefor time ,intherange0to59.
mysql> SELECTMINUTE('2008020310:05:03')
>5
MONTH( date )
Returnsthemonthfor date ,intherange1to12forJanuarytoDecember,or0fordatessuchas'00000000'
or'20080000'thathaveazeromonthpart.
mysql> SELECTMONTH('20080203')
>2
MONTHNAME( date )
Returnsthefullnameofthemonthfor date .AsofMySQL5.0.25,thelanguageusedforthenameiscontrolled
bythevalueofthelc_time_namessystemvariable(Section10.7,MySQLServerLocaleSupport).
mysql> SELECTMONTHNAME('20080203')
>'February'
NOW()
Returnsthecurrentdateandtimeasavaluein'YYYYMMDDHH:MM:SS'orYYYYMMDDHHMMSS.uuuuuuformat,
dependingonwhetherthefunctionisusedinastringornumericcontext.Thevalueisexpressedinthecurrent
timezone.
mysql> SELECTNOW()
>'2007121523:50:26'
mysql> SELECTNOW()+0
>20071215235026.000000
NOW()returnsaconstanttimethatindicatesthetimeatwhichthestatementbegantoexecute.(Withinastored
functionortrigger,NOW()returnsthetimeatwhichthefunctionortriggeringstatementbegantoexecute.)This
differsfromthebehaviorforSYSDATE(),whichreturnstheexacttimeatwhichitexecutesasofMySQL5.0.12.
mysql> SELECTNOW(),SLEEP(2),NOW()
++++
|NOW()|SLEEP(2)|NOW()|
++++
|2006041213:47:36|0|2006041213:47:36|
++++
mysql> SELECTSYSDATE(),SLEEP(2),SYSDATE()
++++
|SYSDATE()|SLEEP(2)|SYSDATE()|
++++
|2006041213:47:44|0|2006041213:47:46|
++++
Inaddition,theSETTIMESTAMPstatementaffectsthevaluereturnedbyNOW()butnotbySYSDATE().This
meansthattimestampsettingsinthebinaryloghavenoeffectoninvocationsofSYSDATE().Settingthe
timestamptoanonzerovaluecauseseachsubsequentinvocationofNOW()toreturnthatvalue.Settingthe
timestamptozerocancelsthiseffectsothatNOW()onceagainreturnsthecurrentdateandtime.
SeethedescriptionforSYSDATE()foradditionalinformationaboutthedifferencesbetweenthetwofunctions.
PERIOD_ADD( P , N )
Adds N monthstoperiod P (intheformatYYMMorYYYYMM).ReturnsavalueintheformatYYYYMM.Notethatthe
periodargument P isnotadatevalue.
mysql> SELECTPERIOD_ADD(200801,2)
>200803
PERIOD_DIFF( P1 , P2 )
Returnsthenumberofmonthsbetweenperiods P1 and P2 . P1 and P2 shouldbeintheformatYYMMorYYYYMM.
Notethattheperiodarguments P1 and P2 arenotdatevalues.
mysql> SELECTPERIOD_DIFF(200802,200703)
>11
QUARTER( date )
Returnsthequarteroftheyearfor date ,intherange1to4.
mysql> SELECTQUARTER('20080401')
>2
SECOND( time )
Returnsthesecondfor time ,intherange0to59.
mysql> SELECTSECOND('10:05:03')
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
8/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
>3
SEC_TO_TIME( seconds )
Returnsthe seconds argument,convertedtohours,minutes,andseconds,asaTIMEvalue.Therangeofthe
resultisconstrainedtothatoftheTIMEdatatype.Awarningoccursiftheargumentcorrespondstoavalue
outsidethatrange.
mysql> SELECTSEC_TO_TIME(2378)
>'00:39:38'
mysql> SELECTSEC_TO_TIME(2378)+0
>3938
RangecheckingonthepartsofdatevaluesisasdescribedinSection11.3.1,TheDATE,DATETIME,and
TIMESTAMPTypes.Thismeans,forexample,thatzerodatesordateswithpartvaluesof0arepermitted
unlesstheSQLmodeissettodisallowsuchvalues.
mysql> SELECTSTR_TO_DATE('00/00/0000','%m/%d/%Y')
>'00000000'
mysql> SELECTSTR_TO_DATE('04/31/2004','%m/%d/%Y')
>'20040431'
Note
Youcannotuseformat"%X%V"toconvertayearweekstringtoadatebecausethecombinationofayearand
weekdoesnotuniquelyidentifyayearandmonthiftheweekcrossesamonthboundary.Toconvertayearweek
toadate,youshouldalsospecifytheweekday:
mysql> SELECTSTR_TO_DATE('200442Monday','%X%V%W')
>'20041018'
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
9/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
SYSDATE()
Returnsthecurrentdateandtimeasavaluein'YYYYMMDDHH:MM:SS'orYYYYMMDDHHMMSS.uuuuuuformat,
dependingonwhetherthefunctionisusedinastringornumericcontext.
AsofMySQL5.0.12,SYSDATE()returnsthetimeatwhichitexecutes.ThisdiffersfromthebehaviorforNOW(),
whichreturnsaconstanttimethatindicatesthetimeatwhichthestatementbegantoexecute.(Withinastored
functionortrigger,NOW()returnsthetimeatwhichthefunctionortriggeringstatementbegantoexecute.)
mysql> SELECTNOW(),SLEEP(2),NOW()
++++
|NOW()|SLEEP(2)|NOW()|
++++
|2006041213:47:36|0|2006041213:47:36|
++++
mysql> SELECTSYSDATE(),SLEEP(2),SYSDATE()
++++
|SYSDATE()|SLEEP(2)|SYSDATE()|
++++
|2006041213:47:44|0|2006041213:47:46|
++++
Inaddition,theSETTIMESTAMPstatementaffectsthevaluereturnedbyNOW()butnotbySYSDATE().This
meansthattimestampsettingsinthebinaryloghavenoeffectoninvocationsofSYSDATE().
BecauseSYSDATE()canreturndifferentvaluesevenwithinthesamestatement,andisnotaffectedbySET
TIMESTAMP,itisnondeterministicandthereforeunsafeforreplication.Ifthatisaproblem,youcanstarttheserver
withthesysdateisnowoptiontocauseSYSDATE()tobeanaliasforNOW().Thenondeterministicnatureof
SYSDATE()alsomeansthatindexescannotbeusedforevaluatingexpressionsthatrefertoit.
TIME( expr )
Extractsthetimepartofthetimeordatetimeexpression expr andreturnsitasastring.
mysql> SELECTTIME('2003123101:02:03')
>'01:02:03'
mysql> SELECTTIME('2003123101:02:03.000123')
>'01:02:03.000123'
expressions,butbothmustbeofthesametype.
TheresultreturnedbyTIMEDIFF()islimitedtotherangeallowedforTIMEvalues.Alternatively,youcanuse
eitherofthefunctionsTIMESTAMPDIFF()andUNIX_TIMESTAMP(),bothofwhichreturnintegers.
mysql> SELECTTIMEDIFF('2000:01:0100:00:00',
> '2000:01:0100:00:00.000001')
>'00:00:00.000001'
mysql> SELECTTIMEDIFF('2008123123:59:59.000001',
> '2008123001:01:01.000002')
>'46:58:57.999999'
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
10/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
mysql> SELECTTIMESTAMPADD(MINUTE,1,'20030102')
>'2003010200:01:00'
mysql> SELECTTIMESTAMPADD(WEEK,1,'20030102')
>'20030109'
TheorderofthedateordatetimeargumentsforthisfunctionistheoppositeofthatusedwiththeTIMESTAMP()
functionwheninvokedwith2arguments.
TIME_FORMAT( time , format )
ThisisusedliketheDATE_FORMAT()function,butthe format stringmaycontainformatspecifiersonlyforhours,
minutes,seconds,andmicroseconds.OtherspecifiersproduceaNULLvalueor0.
Ifthe time valuecontainsanhourpartthatisgreaterthan23,the%Hand%khourformatspecifiersproducea
valuelargerthantheusualrangeof0..23.Theotherhourformatspecifiersproducethehourvaluemodulo12.
mysql> SELECTTIME_FORMAT('100:00:00','%H%k%h%I%l')
>'10010004044'
TIME_TO_SEC( time )
Returnsthe time argument,convertedtoseconds.
mysql> SELECTTIME_TO_SEC('22:23:00')
>80580
mysql> SELECTTIME_TO_SEC('00:39:38')
>2378
TO_DAYS( date )
Givenadate date ,returnsadaynumber(thenumberofdayssinceyear0).
mysql> SELECTTO_DAYS(950501)
>728779
mysql> SELECTTO_DAYS('20071007')
>733321
TO_DAYS()isnotintendedforusewithvaluesthatprecedetheadventoftheGregoriancalendar(1582),
becauseitdoesnottakeintoaccountthedaysthatwerelostwhenthecalendarwaschanged.Fordatesbefore
1582(andpossiblyalateryearinotherlocales),resultsfromthisfunctionarenotreliable.SeeSection12.8,
WhatCalendarIsUsedByMySQL?,fordetails.
RememberthatMySQLconvertstwodigityearvaluesindatestofourdigitformusingtherulesinSection11.3,
DateandTimeTypes.Forexample,'20081007'and'081007'areseenasidenticaldates:
mysql> SELECTTO_DAYS('20081007'),TO_DAYS('081007')
>733687,733687
InMySQL,thezerodateisdefinedas'00000000',eventhoughthisdateisitselfconsideredinvalid.This
meansthat,for'00000000'and'00000101',TO_DAYS()returnsthevaluesshownhere:
mysql> SELECTTO_DAYS('00000000')
++
|to_days('00000000')|
++
|NULL|
++
1rowinset,1warning(0.00sec)
mysql> SHOWWARNINGS
++++
|Level|Code|Message|
++++
|Warning|1292|Incorrectdatetimevalue:'00000000'|
++++
1rowinset(0.00sec)
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
11/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
mysql> SELECTTO_DAYS('00000101')
++
|to_days('00000101')|
++
|1|
++
1rowinset(0.00sec)
ThisistruewhetherornottheALLOW_INVALID_DATESSQLservermode(availableinMySQL5.0.2andlater)is
enabled.
UNIX_TIMESTAMP(),UNIX_TIMESTAMP( date )
Ifcalledwithnoargument,returnsaUnixtimestamp(secondssince'1970010100:00:00'UTC)asan
unsignedinteger.IfUNIX_TIMESTAMP()iscalledwitha date argument,itreturnsthevalueoftheargumentas
secondssince'1970010100:00:00'UTC. date maybeaDATEstring,aDATETIMEstring,aTIMESTAMP,or
anumberintheformatYYMMDDorYYYYMMDD.Theserverinterprets date asavalueinthecurrenttimezoneand
convertsittoaninternalvalueinUTC.ClientscansettheirtimezoneasdescribedinSection10.6,MySQL
ServerTimeZoneSupport.
mysql> SELECTUNIX_TIMESTAMP()
>1196440210
mysql> SELECTUNIX_TIMESTAMP('2007113010:30:19')
>1196440219
WhenUNIX_TIMESTAMP()isusedonaTIMESTAMPcolumn,thefunctionreturnstheinternaltimestampvalue
directly,withnoimplicitstringtoUnixtimestampconversion.Ifyoupassanoutofrangedateto
UNIX_TIMESTAMP(),itreturns0.
Note:IfyouuseUNIX_TIMESTAMP()andFROM_UNIXTIME()toconvertbetweenTIMESTAMPvaluesandUnix
timestampvalues,theconversionislossybecausethemappingisnotonetooneinbothdirections.Forexample,
duetoconventionsforlocaltimezonechanges,itispossiblefortwoUNIX_TIMESTAMP()tomaptwoTIMESTAMP
valuestothesameUnixtimestampvalue.FROM_UNIXTIME()willmapthatvaluebacktoonlyoneoftheoriginal
TIMESTAMPvalues.Hereisanexample,usingTIMESTAMPvaluesintheCETtimezone:
mysql> SELECTUNIX_TIMESTAMP('2005032703:00:00')
++
|UNIX_TIMESTAMP('2005032703:00:00')|
++
|1111885200|
++
mysql> SELECTUNIX_TIMESTAMP('2005032702:00:00')
++
|UNIX_TIMESTAMP('2005032702:00:00')|
++
|1111885200|
++
mysql> SELECTFROM_UNIXTIME(1111885200)
++
|FROM_UNIXTIME(1111885200)|
++
|2005032703:00:00|
++
IfyouwanttosubtractUNIX_TIMESTAMP()columns,youmightwanttocasttheresulttosignedintegers.See
Section12.10,CastFunctionsandOperators.
UTC_DATE,UTC_DATE()
ReturnsthecurrentUTCdateasavaluein'YYYYMMDD'orYYYYMMDDformat,dependingonwhetherthe
functionisusedinastringornumericcontext.
mysql> SELECTUTC_DATE(),UTC_DATE()+0
>'20030814',20030814
UTC_TIME,UTC_TIME()
ReturnsthecurrentUTCtimeasavaluein'HH:MM:SS'orHHMMSS.uuuuuuformat,dependingonwhetherthe
functionisusedinastringornumericcontext.
mysql> SELECTUTC_TIME(),UTC_TIME()+0
>'18:07:53',180753.000000
UTC_TIMESTAMP,UTC_TIMESTAMP()
ReturnsthecurrentUTCdateandtimeasavaluein'YYYYMMDDHH:MM:SS'orYYYYMMDDHHMMSS.uuuuuu
format,dependingonwhetherthefunctionisusedinastringornumericcontext.
mysql> SELECTUTC_TIMESTAMP(),UTC_TIMESTAMP()+0
>'2003081418:08:04',20030814180804.000000
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
12/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
Sunday
053
withaSundayinthisyear
Monday
053
with4ormoredaysthisyear
Sunday
153
withaSundayinthisyear
Monday
153
with4ormoredaysthisyear
Sunday
053
with4ormoredaysthisyear
Monday
053
withaMondayinthisyear
Sunday
153
with4ormoredaysthisyear
Monday
153
withaMondayinthisyear
Notethatifadatefallsinthelastweekofthepreviousyear,MySQLreturns0ifyoudonotuse2,3,6,or7asthe
optional mode argument:
mysql> SELECTYEAR('20000101'),WEEK('20000101',0)
>2000,0
OnemightarguethatWEEK()shouldreturn52becausethegivendateactuallyoccursinthe52ndweekof1999.
WEEK()returns0insteadsothatthereturnvalueistheweeknumberinthegivenyear.Thismakesuseofthe
WEEK()functionreliablewhencombinedwithotherfunctionsthatextractadatepartfromadate.
Ifyoupreferaresultevaluatedwithrespecttotheyearthatcontainsthefirstdayoftheweekforthegivendate,
use0,2,5,or7astheoptional mode argument.
mysql> SELECTWEEK('20000101',2)
>52
Alternatively,usetheYEARWEEK()function:
mysql> SELECTYEARWEEK('20000101')
>199952
mysql> SELECTMID(YEARWEEK('20000101'),5,2)
>'52'
WEEKDAY( date )
Returnstheweekdayindexfor date (0=Monday,1=Tuesday,6=Sunday).
mysql> SELECTWEEKDAY('2008020322:23:00')
>6
mysql> SELECTWEEKDAY('20071106')
>1
WEEKOFYEAR( date )
Returnsthecalendarweekofthedateasanumberintherangefrom1to53.WEEKOFYEAR()isacompatibility
functionthatisequivalenttoWEEK( date ,3).
mysql> SELECTWEEKOFYEAR('20080220')
>8
YEAR( date )
Returnstheyearfor date ,intherange1000to9999,or0forthezerodate.
mysql> SELECTYEAR('19870101')
>1987
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
13/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
NotethattheweeknumberisdifferentfromwhattheWEEK()functionwouldreturn(0)foroptionalarguments0or
1,asWEEK()thenreturnstheweekinthecontextofthegivenyear.
Previous/Next/Up/TableofContents
UserComments
PostedbyIsaacShepardonOctober1120032:53pm
[Delete][Edit]
Ifyou'relookingforgenericSQLqueriesthatwillallowyoutogetthedays,months,andyearsbetweenanytwogivendates,youmightconsiderusingthese.Youjust
needtosubstitutedate1anddate2withyourdateexpressions.
NOTE:Someoftheseformulasarecomplexbecausetheyaccountforallcaseswheredate1<date2,date1=date2,anddate1>date2.Additionally,theseformulas
canbeusedinverygenericquerieswherealiasesandtemporaryvariablesarenotallowed.
Numberofdaysbetweendate1anddate2:
TO_DAYS(date2)TO_DAYS(date1)
Numberofmonthsbetweendate1anddate2:
IF((((YEAR(date2)1)*12+MONTH(date2))((YEAR(date1)1)*12+MONTH(date1)))>0,(((YEAR(date2)1)*12+MONTH(date2))((YEAR(date1)1)*12+
MONTH(date1)))(MID(date2,9,2)<MID(date1,9,2)),IF((((YEAR(date2)1)*12+MONTH(date2))((YEAR(date1)1)*12+MONTH(date1)))<0,
(((YEAR(date2)1)*12+MONTH(date2))((YEAR(date1)1)*12+MONTH(date1)))+(MID(date1,9,2)<MID(date2,9,2)),(((YEAR(date2)1)*12+
MONTH(date2))((YEAR(date1)1)*12+MONTH(date1)))))
Numberofyearsbetweendate1anddate2:
IF((YEAR(date2)YEAR(date1))>0,(YEAR(date2)YEAR(date1))(MID(date2,6,5)<MID(date1,6,5)),IF((YEAR(date2)YEAR(date1))<0,(YEAR(date2)
YEAR(date1))+(MID(date1,6,5)<MID(date2,6,5)),(YEAR(date2)YEAR(date1))))
Nowforsomecommentsaboutthese.
1.Theseresultsreturnintegernumberofyears,months,anddays.Theyare"floored."Thus,1.4dayswoulddisplayas1day,and13.9yearswoulddisplayas13
years.Likewise,1.4yearswoulddisplayas1year,and13.9monthswoulddisplayas13months.
2.NotethatIusebooleanexpressionsinmanycases.Becausebooleanexpressionsevaluateto0or1,Icanusethemtosubtractoradd1fromthetotalbasedona
condition.
Forexample,tocalculatethenumberofyearsbetweentodates,firstsimplysubtracttheyears.Theproblemisthatdoingsoisn'talwayscorrect.Considerthenumber
ofyearsbetweenJuly1,1950andMay1,1952.Technically,thereisonlyonefullyearbetweenthem.OnJuly1,1952andlater,therewillbetwoyears.Therefore,
youshouldsubtractoneyearincasethedatehasn'tyetreachedafullyear.Thisisdonebycheckingtheifthesecondmonthdayisbeforethefirstmonth
day.Ifso,thisresultsinavalueof1,whichissubtractedfromthetotal.TheIFstatementsareintheformulabecausewemustaddoneyearwhendealingwiththe
datesintheoppositeorder,andwemustnotaddorsubtractanythingwhenthedifferenceofthedateyearsiszero.
3.Togetthemonthday,IuseMID.Thisisbetter
thanusingRIGHT,sinceitwillworkforbothdates
anddatetimes.
4.Unlikemanyothersolutions,thesequeriesshould
workwithdatespriorto01/01/1970.
Postedby[namewithheld]onFebruary620034:19pm
[Delete][Edit]
Spentsometimetryingtoworkouthowtocalculatethemonthstartxmonthsago(sothatIcancreatehistoricalstatsonthefly)
hereiswhatIcameupwith..
((PERIOD_ADD(EXTRACT(YEAR_MONTHFROMCURDATE()),6)*100)+1)
thisgivesyouthefirstdayofthemonthsixmonthsbeforethestartofthecurrentmonthindatetimeformat
PostedbyfilipwolakonAugust420036:44am
[Delete][Edit]
Severaltimesihavecometoafollowngdate/timeproblem:
Inthetableiamstoringbothdateandtimeinformationinthedatetimecolumn.Querying,IwanttoreceiveCOUNTedresultsgroupedbydate,andnotdateandtime.I
cametotheeasysolution:
SELECTDATE_FORMAT(postdate,'%Y%m%d')ASdd,COUNT(id)FROMMyTableGROUPBYdd
Isupposethissolutiontobequiteslow(dateformatting).
Later,i'upgraded'thisquerytousethestringfunction:
SELECTsubstring(postdate,1,10)ASdd,COUNT(id)FROMMyTableGROUPBYdd
knowing,thattheresultisinthefixedformat.Worksfaster.
PostedbyStoyanStefanovonAugust1620038:05pm
[Delete][Edit]
Hopethiswillhelpsomebody.ThewayIfoundtosumtime:
SELECTSEC_TO_TIME(SUM(TIME_TO_SEC(`time`)))AStotal_timeFROMtime_table
PostedbyGerardMankoonDecember1720039:27am
[Delete][Edit]
ComparingDateswhenusingMSAccessandMyODBC
IfyouareusingMSAccessandhavecreatedAccessqueriestosubstituteforviews(whicharenotyetavailableinmySQL),youcanusethefollowingsyntaxro
performdatecomparisonsandavoidthedreaded"ODBCcallfailed"error:
Select*from[TaskEffortSummary]
Where((Date()+0)>CLng([TaskEffortSummary].[s_end]))
Thisparticularexampleretunstasksthatareoverdue(wheretodaysdateispastthescheduledenddate).ThisquerywasdevelopedforreportsonaTUTOS
database.
Postedby[namewithheld]onJanuary920047:59pm
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
[Delete][Edit]
14/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
NotethatthebuiltindefaultvaluesfortheDATEandDATEFIELDcolumntypesisoutofrange.Forexample,00000000isavalidwayofexpressingNULL,butifthe
columnissetasNOTNULL,00000000isstillthedefaultvalue.ThiscancauseproblemswithsomeapplicationsusingMySQL.
PostedbyasdacfddsfdsfonJanuary2720043:25am
[Delete][Edit]
Iwaslookingforafunctiontodetectifthecurrentweekisoddoreven.IcouldnotfindonesoIusethis:
MOD((DATE_FORMAT(CURDATE(),"%v")),2)
Theoutputisa'0'(even)ora'1'(odd)
PostedbySteveWestonFebruary15200410:49pm
[Delete][Edit]
TocreateaDATETIMEofNOW()inUTCwithoutupgradingto4.1.1,justuse:
DATE_ADD('19700101',INTERVALUNIX_TIMESTAMP()SECOND)
Postedby[namewithheld]onMarch420049:39am
[Delete][Edit]
workaroundforSTR_TO_DATEpreversion4.1.1.uglybutitseemstoworkfine.
assumption:youknowtheformatofthereceiveddate(inthebelowexampletheformatismm/dd/yy,m/d/yy,mm/dd/yyyy,etc)
thestatementextractstheyearbylocatingtheindexofthesecond'/'andreadingfromtherightofthestringtothatindex.theindexofthesecondis'/'isfoundby
usingLOCATEwiththeindexofthefirst'/'.
itextractsthedaybylocatingtheindecesofthefirstandsecond'/'andreadingbetweenthem
itextractsthemonthbylocatingtheindexofthefirst'/'andreadingfromtheleftofthestringtothatindex.
itthenCONCATstheyearmonthanddaypiecestogetherseparatingthemwithhyphens.
lastly,itletsDATE_FORMATdoitsmagiconthestring.
(replacetheteststring'1/11/03'withyourfieldname,etc)
selectDATE_FORMAT(CONCAT(RIGHT('1/11/03',length('1/11/03')LOCATE('/','1/11/03',LOCATE('/','1/11/03')+1)),'',LEFT('1/11/03',LOCATE('/',
'1/11/03')1),'',SUBSTRING('1/11/03',LOCATE('/','1/11/03')+1,LOCATE('/','1/11/03',LOCATE('/','1/11/03')+1)LOCATE('/','1/11/03')1)),'%Y%m
%d')
PostedbyOlavAlexanderMjeldeonMarch15200411:15am
[Delete][Edit]
Letssayyouhavethemysqlbefore4.1.1(wheretimediff()wasimplementet),andyouwanttodoatimediff.
Iwantedtomakea"activeusers"onmypage,butIfoundoutthatIdidnthavethetimedifffunction(tofindpersonswhichhavebeenactivewithin5minutes).
So,Ifiguredthisqueryout:
SELECTnickFROM`users`WHERETO_DAYS(NOW())TO_DAYS(last_login)<=1ANDDATE_FORMAT(CURRENT_TIMESTAMP(),'%H%i')
DATE_FORMAT(last_login,'%H%i')<=5ORDERBY`nick`ASC
itselectsthefieldnick(whichistheonlyonetobedisplayd)andthenitfiltersfor1dayorlessinageofactivity.afterthat,itfiltersfor5minutesorlessinactivity.
firstyouneedtofilterawaytheotherdays,oryourscriptmightgetfooledtothinkthatyesterdaysloginwastodays.
I'mcurrentlyusingthis,anditworksfine!
ontheotherpage,youofcourseneedtoupdatethetimestampfield(whensessionexcists,onreload)
PostedbyChericeScharfonApril5200411:24am
[Delete][Edit]
HereisanexampletoconvertvarioususerinputsforadatefieldonanASPpage(VBScript)thatwillconvertcommonformats(i.e.,m/d/yy,mm/dd/yyyy,etc.)to
MySQLdatabaseformatof(yyyymmdd).Thefunctionbeginsbyestablishingthatthereisadateinthefield.Thensplitsthedate(convertedtostring)intothreeparts
bylocating"/".DateArray(0),DateArray(1),DateArray(2)holdthemonth,dayandyear,respectively.Thesearethencheckedfortheamountofdigits,iftherearenot
enoughdigitsinmonthordaythenaleadingzeroisadded.Ifthereareonlytwodigitsontheyear(ie"04")thenaleading"20"isadded.
FunctionConvertInputDate(varDate)
If(Len(Trim(varDate))>0)Then
DateArray=Split(CStr(varDate),"/")
IFLen(Trim(DateArray(0)))<2Then
DateArray(0)="0"&DateArray(0)
EndIf
IfLen(Trim(DateArray(1)))<2Then
DateArray(1)="0"&DateArray(1)
EndIf
IfLen(Trim(DateArray(2)))<4ThenDateArray(2)="20"&DateArray(2)
EndIf
varDate=DateArray(2)&""&DateArray(0)&""&DateArray(1)
EndIf
EndFunction
*Pleasenoteifauserdoesnotusetwoslashesthisfunctionwillnotwork.Itisbesttoindicate"mm/dd/yy"nearthelabelonthepage.Itwilltake4/6/04,10/6/04,
3/16/2004andallcombinationswithtwoslashes.
PostedbyJasonRichardonApril920047:20am
[Delete][Edit]
IhadaproblemwithmyloginscriptusingPHPandMySQLwhendaylightsavingstime(DST)camearoundthisyear.
IwasusingMYSQLNOW()functiontoaddthecurrentdateandtimetotheuser'srecordintoadatetimefield.WhenDSTcameintoeffectnewlyenteredlogintimes
wereanhourslow(I'minEST).Sincethelastloginistobeupdatedonlyifanhourormorehaspassedsincethelastloginthiswasabigproblem!
TheproblemisthatPHPtakesDSTintoaccountandMySQLdoesnot(asfarasIknow)andIwasenteringthetimeusingMySQL'sNOW()functionandthen
comparingthevaluereturnedbyPHP'stime()function.
Averysimplesolutiontothisisthefollowing.NotethePHPtimeformatstring'YmdHis'itformatstoYYYYMMDDHHMMSSwhichiswhatMySQLexpectsfora
date/timefield.
$now=time()
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
15/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
$lastLogin=strtotime($row['lastLogin'])
$diff=$now$lastLogin
$now=date('YmdHis',$now)
if($diff>3600){//3600secondsis1hour
$query='UPDATEmembersSETlogins=logins+1,lastLogin='.$now.'WHEREmemberID='.$SEC_ID
mysql_query($query)
}
NowthedateenteredisthePHPtime(thataccountsforDST)andwearecomparingittoPHPtimesoalliswell.
IthinkthisapproachwillworkwellforanytimeyouwishtoenteradateintoMySQLusingPHP.Justformatthedateusingthe"YmdHis"formatstringandusethe
strtotime()functiontoreadadateretrievedfromMySQL.
Theadvantagetothisapproachratherthanjustenteringthe"normal"PHPdateintoacharortextfieldisthatthedatesare"human"readableinthetableandallthe
MySQLdate/timefunctionsareavailableforfuturequeries.
PostedbyMartinSchwedesonApril2520049:11am
[Delete][Edit]
tolocalizetheweekday:
SELECTELT(WEEKDAY('20040410')+1,'Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag','Sonntag')
longversionwithmonth:
SELECTDATE_FORMAT('20040410',CONCAT(ELT(WEEKDAY('20040410')+1,'Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag','Sonntag'),',%d.',
ELT(MONTH('20040410'),'Januar','Februar','Mrz','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'),'%Y'))
>Samstag,10.April2004
sameforunixtimestamp:
SELECTDATE_FORMAT(FROM_UNIXTIME(1081548000),CONCAT(ELT(WEEKDAY(FROM_UNIXTIME(1081548000))+1,'Mo','Di','Mi','Do','Fr','Sa','So'),',%d.',
ELT(MONTH(FROM_UNIXTIME(1081548000)),'Jan.','Feb.','Mrz','April','Mai','Juni','Juli','Aug.','Sept.','Okt.','Nov.','Dez.'),'%Y'))
>Sa,10.April2004
PostedbyPhilippePoelvoordeonApril3020045:50am
[Delete][Edit]
Ihadtoqueryatableandretrieverowsthatwereaddedonlytoday,so:
selectidfrommy_table
where
timestamp<date_format(date_add(CURRENT_TIMESTAMP(),interval1day),'%Y%m%d000000')
AND
timestamp>=date_format(CURRENT_TIMESTAMP(),'%Y%m%d000000')
startingwithMySQL4.0,youcouldalsousetheBETWEEN...ANDsyntax.
Ifanyonehasabetterquerytodothat,letmeknow.
PostedbyMichaelMarcusonMay120042:41pm
[Delete][Edit]
AfterreadingnumerousarticlesandpostsregardingconvertingbackandforthbetweenSQLdatetimeandVBscriptdatetime,Ioptedforthesimplestsolutionformy
databases.Isimplysavealldatetimevaluesinvarchar(20)fieldsandcalloneitherMySQLorVBscriptfunctionstogetdatetimevaluesorcheck/convertdatetime
values.Forexample:
currentDT=CStr(cn.execute("SELECTNOW()").Fields(0).Value)
willfetchcurrentdatetimeintheSQLserver'sdatetimeformatandthenconvertittoastring.[Obviously,cnissetbySetcn=
Server.CreateObject("ADODB.Connection")tocreatethedatabaseconnection,thenthedatabaseisopenedwithacn.open(parameters).]
Youcanthensavethisstringtoanappropriatefieldsuchas'flddate_added'whichisformattedasvarchar(20).
Whenretrievingtheflddate_addedvalue,youcanusethisVBscriptcodetocheckifthevalueisindeedadatetimevalueandconvertittothedatetimeformatofthe
user'scomputer"
ifIsDate(flddate_added)then
=CDate(flddate_added)'converttouser'ssystemformatfordisplayusinguser'scodepage
else
=flddate_added'justdisplaythestring
endif
TheabovemethodsallowmetogetaroundalloftheissuesregardingVBscript'sdatetimedisplayformatdifferencesdependingonthesystemlocal.
PostedbyRayMorrisonJuly1520044:37pm
[Delete][Edit]
PostedbyFilipWolak:
>Severaltimesihavecometoafollowngdate/timeproblem:
>Inthetableiamstoringbothdateandtimeinformationinthedatetime
>column.Querying,IwanttoreceiveCOUNTedresultsgroupedbydate,
>andnotdateandtime.
...
>SELECTsubstring(postdate,1,10)...
Ifit'saDATETIMEcolumnthansubstringisnotappropriate
it'slogicallynonsensicalofcourse,andjusthappenstowork
insomeversionofMySQLbecausetheDATETIMEhappens
toberepresentedbyastringinsomecontexts.
BetterwouldbetotreattheDATETIMEasaDATETIME
ratherthanasastring,whichwillworkinfutureversions
ofMYSQLandinotherRDMS:
SELECTDATE(postdate)...
PostedbyDavidLyononJuly1720044:12pm
[Delete][Edit]
HereisanotherVB/ASPfunctionforconvertingDatesfromstandardtoMySQLformat.Cherisegaveaniceexampleabove,butithasextracomplexityduetotheuse
ofarraysandalsomaybepronedtouserinputerrors.
ThefollowingexamplewillworkbasedontheLocalizationsettingsoftheserveronwhichitisrun.Soitshouldn'tcarewhetherthedateisddmmyyyy,mm/dd/yy,
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
16/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
mm/dd/yyyy,mdyy,etc.Justmakesureyoupassitadatevaluethatisformattedcomplianttotheserver'slocalization.IfnecessaryuseVB'sCDate(strDateValue)
beforepassingstrDateValuetothefunction.
YoucanalsoeasilymodifythisfunctiontodothesameforTimevalues,exceptyouuseHour,Minute,andSecondVBfunctions,anddelimitwithacolon(:)insteadof
adash().
Hopethishelps!
FunctionfuncMySqlDate(dtmChangeDate)
'CONVERTSLOCALIZEDDATEFORMAT(forexample:m/d/yy)TOMySQLFORMAT(yyyymmdd)
DimstrTempYear,strTempMonth,strTempDay
strTempYear=Year(dtmChangeDate)
strTempMonth=Month(dtmChangeDate)
strTempDay=Day(dtmChangeDate)
ifLen(strTempYear)=2then'Y2KTEST19382037ADJUSTASNECESSARY
ifstrTempYear>=38then
strTempYear="19"&strTempYear
else
strTempYear="20"&strTempYear
endif
endif
ifstrTempMonth<10thenstrTempMonth="0"&strTempMonth
ifstrTempDay<10thenstrTempDay="0"&strTempDay
funcMySqlDate=strTempYear&""&strTempMonth&""&strTempDay
EndFunction
PostedbyBenjaminZagelonAugust5200412:44pm
[Delete][Edit]
Tofindoutthelastdayofamonthuse:
SELECT(DATE_FORMAT('20040120','%Y%m01')INTERVAL1DAY)+INTERVAL1MONTH
Ittooksmeafewtimetohavethisidea,butitworks.Ifyouwanttohavethefirstdayofamonthuse:
SELECTDATE_FORMAT('20040120','%Y%m01')
Tofindoutthefirstdayofamonthwasmyfirstdevelopmentstep,thenitwaseasytoextractthelastdayofamonth.ItisusefullforaccountingforserviceswhereI
needthissolution.
Greetings
PostedbyMarkStaffordonAugust620045:26pm
[Delete][Edit]
Iseetheuseforboth,butIfindthislayoutmoreusefulasareferencetool:
++++
|metric|variant|result|
++++
|microseconds|%f|000000..999999|
|seconds|%sor%S|00..59|
|minutes|%i|00..59|
|hours|%H|00...23|
||%hor%I|00...12|
||%k|0...23|
||%l|1...12|
|day|%a|Sun...Sat|
||%D|1st,2nd,3rd|
||%d|0.31|
||%e|0..31|
||%j|001...366|
||%W|Sunday...Sat|
||%w|0...6|
|week|%U|00...53perSun|
||%u|00...53perMon|
|*|%V|01...53perSun|
|*|%v|01...53perMon|
|month|%b|Jan...Dec|
||%c|0...12|
||%M|January...December|
||%m|00...12|
|year|%Y|1999|
||%y|99|
|*|%X|1999|
|*|%x|99|
|time|%r|01:31:12pm|
|||%T|01:31:12pm|
||%p|AMorPM|
|Percentsign|%%|%|
++++
PostedbyMlonAugust720046:53pm
[Delete][Edit]
SelectrecordsthatareolderthanXdaysfromthecurrentdatewheresent_timeisaTimestampdatatypefield.
selectIDfromMESSAGEwhereSENT_TIME<(CURDATE()INTERVAL5DAY)
PostedbyRConAugust2420047:21pm
[Delete][Edit]
Ifyoudonothave4.xxyethereisasimplewaytogetthelastdayofthemonth.Youcanreplacethecurrentdatewithavartofindthelastdayofanymonth.
SELECT
SUBDATE(ADDDATE(CURDATE(),INTERVAL1MONTH),INTERVALDAYOFMONTH(CURDATE())DAY)ASLAST_DAY_MONTH
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
17/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
seemstoworkwell.
PostedbyMartinAlgestenonSeptember920042:00pm
[Delete][Edit]
>Severaltimesihavecometoafollowngdate/timeproblem:
>Inthetableiamstoringbothdateandtimeinformationinthe
>datetimecolumn.Querying,IwanttoreceiveCOUNTedresults
>groupedbydate,andnotdateandtime.Icametotheeasy
>solution:
Ineededaqueryforamoregeneralcasetodotimebasedreportingonarbitrarybig"slices"oftimestampeddata.
Mytablehasacolumn'timestamp'whichisoftype'datetime'.
Thefollowingmakes'120'secondbigslices
selectfrom_unixtime(unix_timestamp(timestamp)unix_timestamp(timestamp)%120)asslice,...groupbyslice
PostedbyDavidBerryonSeptember1720047:08pm
[Delete][Edit]
Iwantedtofindthestartdate(Sunday)andtheenddate(Saturday)foranygivenweekwhenallIhadtogofromisanarbitrarydate(moreprecisely,thecurrent
date).SinceMySQLregistersSundayas1,andSaturdayas7,ifyouwishtoadjustthestartandendpointsonaweek,you'llhavetomodifythefollowingfunctioncalls
appropriately,andchangetheintegers,or(asIhavedone)usevariables:
set@someday=curdate()
set@weekstart=1//Sunday
set@weekend=7//Saturday
endofweek:
selectdate_add(@someday,interval@weekenddayofweek(@someday)day)
beginningofweek:
selectdate_sub(@someday,intervaldayofweek(@someday)@weekstartday)
Ofcourse,Iusethesefunctionsinamorecomplexquerythatfiltersselectresultsfromatablewitha"datetime"field.Thisallowsmetofocusonweeklydata.Avery
neatthingisbeingabletoreplace'curdate()'withadateat(theoretically)anypointintimeontheGregoriancalendar.
PostedbyJeffreyFriedlonOctober3120049:05am
[Delete][Edit]
Thevaluereturnedby
UNIX_TIMESTAMP(NOW())
canbequiteunintuitiveduringthelasthourofdaylightsavingtimeinthefall,asitcanreturnatimestampthat'sanhouraheadofthecurrenttime.(Thedocsindicate
thatthismaybe"fixed"from4.1.3,butIhavenottested.)
ThisisbecauseCSTrelatedinformationislostduringtheconversionbyNOW()fromthecurrenttimetoastring.Whenpresentedadatestringlike"20041031
01:52:37"whichnamesatimethathappenedtwice(onceduringdaylightsavingtime,andagainanhourlaterinstandardtime),itdoesn'tknowwhichyouintenditto
beinterpretedas.
Thedocsindicatethatfrom4.1.3,itusesthetimezoneineffectatthetimeoftheSELECT,whichimpliesthat
FROM_UNIXTIME("2004103101:52:37")
returnsadifferentvaluedependingonwhetheryouarecurrentlyunderdaylightsavingtimeornot.With4.1.2andbefore,itseemstoalwaysusestandardtime,and
hencetheonehour"error"(whichisnotreallyanerror,butdamnunintuitivethatUNIX_TIMESTAMP(NOW())doesnotreturntheUNIX_TIMESTAMPfornow.
NotethatUNIX_TIMESTAMP()withoutargsdoesreturntheproperunixtimestampforthecurrenttime.
PostedbyShamuntohaonDecember18200410:45am
[Delete][Edit]
Ifyouhaveatable1,and(fieldsdatewhichisvarchar(100)
youcanalsoconvertitasdatetypelookthefollowingexample
mysql>selectstr_to_date(date,'%d/%m/%Y')asMydatefromtable1orderbyMydateDESC
++
|Mydate|
++
|20041216|
|20041215|
|20041202|
|20041202|
|20041101|
|20041029|
|20041012|
|20041007|
|20040912|
|20040819|
|20040813|
|20040809|
|20040804|
|20040730|
|20040726|
|20040720|
|20040716|
|20040714|
++
18rowsinset(0.00sec)
mysql>
PostedbyJohnRomanoonJanuary26200510:06pm
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
[Delete][Edit]
18/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
IfyouneedtoEXTRACTtheQUARTERpriortov5.0tryCEILING(EXTRACT(MONTHFROMdate)/3)
PostedbyRobertChristiaanseonJanuary2720052:18pm
[Delete][Edit]
CALCULATINGADATEUSINGAWEEKNUMBER
Ifyouwanttocalculatethedatehavingayear,adayoftheweekandaweeknumber(Let'ssayThursdayofweeknumber4in2005),youcancalculateitlikethis:
SELECTDATE_ADD('20050104',INTERVAL((41)*7+(4DATE_FORMAT('20050104','%w')))DAY)
InPHPitwouldbesomethinglikethis(whenweeksstartonMonday):
$Days=array('xx','ma','di','wo','do','vr','za','zo')
$DayOfWeek=array_search($aDay,$Days)//getdayofweek(1=Monday)
$Year=2005
$Week=4
$query="SELECTDATE_ADD('".$Year."0104',INTERVAL((".$Week."1)*7+(".$DayOfWeek."DATE_FORMAT('".$Year."0104','%w')))DAY)"
January4thischosenasabase,becauseitisalwaysinweeknumber1.(January1stisnotnecessarelyinweek1!)
Youcantestitwiththis:
<?php
//connecttoyourdatabasefirst
$Year=2005;
for($weeknr=0;$weeknr<=53;$weeknr++)
{
for($day=1;$day<=7;$day++)
{
$query="
SELECT
DATE_ADD('".$Year."0104',
INTERVAL((".$weeknr."1)*7+
(".$day."DATE_FORMAT('".$Year."0104','%w')))DAY)
";
$result=mysql_query($query);
if($result)
{
$row=mysql_fetch_row($result);
echo"year=$Yearweekno=$weeknrday=$day:".$row[0].'<br>';
}
else
echo'emptyresultset<br>'.EOL;
}
}
?>
PostedbyRalphNoordanusonFebruary18200512:23pm
[Delete][Edit]
+++
|date1|NOW()|
+++
|2005031716:00:00|2005021813:07:29|
+++
Ifyou'relookingforanSQLquerythatreturnsthenumberofdays,hoursandminutesbetweendate1andnow:
SELECTCONCAT(DAYOFYEAR(date1)DAYOFYEAR(NOW()),'days',DATE_FORMAT(ADDTIME("2000000000:00:00",SEC_TO_TIME(TIME_TO_SEC(date1)
TIME_TO_SEC(NOW()))),'%khoursand%iminutes'))AStimeFROMtime_table
++
|time|
++
|27days2hoursand52minutes|
++
PostedbyLukeBurgessonOctober1520065:56am
[Delete][Edit]
Theredoesn'tappeartobeanofficialwayofselecting*fromatablewhereeg'dateisjanuary2005'.Sofari'vefound8differentways!!
1.wheredatelike'200501%'
2.whereDATE_FORMAT(date,'%Y%m')='200501'
3.whereEXTRACT(YEAR_MONTHFROMdate)='200501'
4.whereYEAR(date)='2005'andMONTH(date)='1'
5.wheresubstring(date,1,7)='200501'
6.wheredatebetween'20050101'and'20050131'
7.wheredate>='20050101'anddate<='20050131'
8.wheredateIN('20050101','20050102','20050103','20050104','20050105','20050106','20050107','20050108','20050109','20050110','200501
11','20050112','20050113','20050114','20050115','20050116','20050117','20050118','20050119','20050120','20050121','20050122','200501
23','20050124','20050125','20050126','20050127','20050128','20050129','20050130','20050131')
PostedbyJoshHaydenonMarch2020052:14am
[Delete][Edit]
Ineededaquerythatwoulddeleteallrowsthatwerecreatedoveranhourago.Here'swhatIused:
Toinserttherow:
INSERTINTO`table_name`(`time_col`)VALUES(NOW())
Todeletetherowscreatedoveranhourago:
DELETEFROM`table_name`WHERE`time_col`<ADDDATE(NOW(),INTERVAL1HOUR)
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
19/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
PostedbyErinQuickLaughlinonMarch29200512:49am
[Delete][Edit]
TotakeChericeScharf'svbexampleonestepfurther,here'stheconversionfromvb'snowformatof'MM/DD/YYHH:MM:SSPM'to'YYYYMMDDHH:MM:SS'for
easyinsertiontothedatetimefield:
FunctionConvertInputDateTime(varDateTime)
If(Len(Trim(varDateTime))>0)Then
DateTimeArray=Split(CStr(varDateTime),"")
varDate=DateTimeArray(0)
varTime=DateTimeArray(1)
varAMPM=DateTimeArray(2)
If(Len(Trim(varDate))>0)Then
DateArray=Split(CStr(varDate),"/")
IFLen(Trim(DateArray(0)))<2Then
DateArray(0)="0"&DateArray(0)
EndIf
IfLen(Trim(DateArray(1)))<2Then
DateArray(1)="0"&DateArray(1)
EndIf
IfLen(Trim(DateArray(2)))<4Then
DateArray(2)="20"&DateArray(2)
EndIf
varDate=DateArray(2)&""&DateArray(0)&""&DateArray(1)
EndIf
If(Len(Trim(varDate))>0)Then
TimeArray=Split(CStr(varTime),":")
IfTrim(varAMPM)="PM"Then
TimeArray(0)=CStr(TimeArray(0)+12)
EndIf
IfLen(Trim(TimeArray(0)))<2Then
TimeArray(0)="0"&TimeArray(0)
EndIf
varTime=TimeArray(0)&":"&TimeArray(1)&":"&TimeArray(2)
EndIf
varDateTime=varDate&""&varTime
EndIf
ConvertInputDateTime=varDateTime
EndFunction
ThanksforthestartingcodeCherice!
PostedbypauladamsonApril120059:30am
[Delete][Edit]
"SELECTid,transactionid,(UNIX_TIMESTAMP(now())UNIX_TIMESTAMP(date))ASdate,sucessful,amountFROMTransactionwheresucessful=1"
toworkoutthedifferencebetweenwhenitwasplacedtonow.
PostedbysantibarionJune1020052:49pm
[Delete][Edit]
GENERATEmissingdaysonatablewithdategaps
=====================================
Ifyouwanttobringvisitsperdaytoyoursiteandyouhaveatable
wich
isstoringthehits,inawaysimilartothis...
+++
|date|IP
+++
|200483|123.123.124.155
|200483|123.123.124.145
|200485|123.123.124.145
+++
Youmaywanttodrawachartandretrieveallthehitsperday.The
problemisthatDAYSWITHOUTHITSWON'TAPPEAR.Andyouwon'tbeable
to
displaytheinfoof'0hits'.
Onesolutiontothiswhichiseasytocodeandclean,istocreateand
haveinyourdatabase,atablenamed'calendar'withallthedaysfrom
todaytillsomeyearsfromnow(let'ssay,till2034).Thetable
should
looksomethinglikethis:
++
|date
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
20/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
++
|200411
|200412
|200413
|200414
|200415
|...
|etc...
++
Hereisapieceofcodewhichwillmakesuchtable:
<?php
mysql_query("CREATETABLE`calendar`(
`id`int(11)NOTNULLauto_increment,
`date`dateNOTNULLdefault'00000000',
PRIMARYKEY(`id`)
)TYPE=MyISAM;");
for($i=0;$i<=(365*30);$i++)
mysql_query("INSERTINTOCALENDARSETdate=date_add(now(),INTERVAL
LAST_INSERT_ID()DAY)");
?>
ThenallyouhavetodoisperformaLEFTJOINfromthistableand
you've
goteverydayfromtheperiodoftimeyouspecify.Eventhosewith0
hits
SELECTcalendar.date,count(*)
FROMcalendar
LEFTJOINvisitsONcalendar.date=visits.date
GROUPBYcalendar.date
PostedbyBenjaminGehrelsonMay1220051:50am
[Delete][Edit]
BecarefullwiththeDAYOFYEARFunctionincomparisions,becauseyouwillrunintoatrapevery4years,whenFeburaryisadayshorter...
PostedbyLabbonMay2020051:24pm
[Delete][Edit]
ToPostedbyErinQuickLaughlinonMarch2920052:49am
Themuchmoreeasierway:
date="YYYY/MM/DDHHSSMM"
date=Replace(date,"/","")
thatsit...
PostedbyJuanSanjuanonMay2320053:36pm
[Delete][Edit]
agefromdateofbirthcomparedwhith
inthisfunctionyoucanknowtheageofaperson(itworksformy).preg12isadateintheformatshowbellowidontknowifitisfast.ifyouhavearecentversionyou
canasigncurtimetoavariableforgetmoreperformanceelseusephp,c++oranothertosaveitas:
YYYYMMDDexample:19970331
left((curtime()preg12),(CHAR_LENGTH(curtime()preg12)4))
anotherwayis:
(TO_DAYS("adate")TO_DAYS("birth"))/365
youcanreplecethecurdateforabeforedatechangingcurdatetothis20000619NOTTHIS:20000619ifyouhavebeterwaysendittomytanksbye.
PostedbyJohnAndersononMay2520058:04pm
[Delete][Edit]
Tocalculateweekendingdategivenanarbitrarydate,usethefollowing(assumesSaturdayisweekend)
SELECTDATE_ADD('20050524',INTERVAL(7DAYOFWEEK('20050524'))DAY)
SELECTDATE_ADD(table.column,INTERVAL(7DAYOFWEEK(table.column))DAY)
PostedbyPe3konJune15200512:51pm
[Delete][Edit]
IfUhaveolderversionofMySQLyoucanreplace'TIMEDIFF(time1,time2)'with
'SEC_TO_TIME((TO_DAYS(time1)*24*3600+TIME_TO_SEC(time1))(TO_DAYS(time2)*24*3600+TIME_TO_SEC(time2)))'
Itiscompletlysame.:)
PostedbyDanielSchroederonJuly1620054:58pm
[Delete][Edit]
Ihadthetasktoselectrowsofatablewherethedateofcreationwasinthefutureofagivendate.
Theproblemwastherewasnodateortimestampfield,buttwofields(int),oneformonthandoneforyear.
SinceIhaveMySQLVersionpriorto4.1.1,wheremostofthenicedate/timefunctionshavebeenadded,Ihadtoworkoutaquerythatbuildsandcomparesdatesout
ofthegivenvalues.
Hereitis:
SELECT*
FROMyour_table
WHERECONCAT(your_table.field_year,'',REPEAT(0,2LENGTH(your_table.field_month)),your_table.field_month,'','01')>=CONCAT({MIN_YEAR},'',REPEAT(0,2
LENGTH({MIN_MONTH})),{MIN_MONTH},'','01')
ORDERBYyour_table.field_year,
your_table.field_month
Inoticedanadvantagecomparedtoworkingwithtimestamps:Youareabletoworkwithdatesbefore1970.
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
21/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
PostedbyOliverPereiraonJuly1920051:40pm
[Delete][Edit]
ThedescriptionofFROM_DAYS(N)"GivenadaynumberN,returnsaDATEvalue"usestheterm"daynumber"withoutexplainingit.
ThedescriptionofTO_DAYS(date)"Givenadatedate,returnsadaynumber(thenumberofdayssinceyear0)"lowerdownthepageatleasttriestoexplainthe
term,butunsuccessfully.
Therearetwoproblemshere.Firstly,therewasnoyear0intheGregoriancalendar.Secondly,anumberofdayshastobecountedfromaday,notayear.Dothey
meanthebeginningofthe(nonexistent)year,ortheendofthe(nonexistent)year?Dononexistentyearsevenhavebeginningsandends?Someoneshouldamend
thesedescriptions.
PostedbyksonAugust1220057:51am
[Delete][Edit]
Here'sanotherquerytogetthenumberofmonthsbetweentwodates:
selectperiod_diff(DATE_FORMAT(date1,'%Y%m'),DATE_FORMAT(date2,'%Y%m'))fromtablexy
PostedbyBobTerrellonAugust2220055:40pm
[Delete][Edit]
Notethatthereiscurrentlynowaytogetthe'AM'or'PM'partofatimeonlyvalueusingthebuiltinfunctions.Youmustfirstconvertittoadatetimeandthenuse
DATE_FORMAT('%p')orperformyourowncalculationsinyourapp.
PostedbyDeronMerandaonAugust3120058:33pm
[Delete][Edit]
Ontransactionalconsistency...Concerningthefunctionswhichusetherealcurrenttime,suchasNOW(),themanualsays"Functionsthatreturnthecurrentdateor
timeeachareevaluatedonlyonceperqueryatthestartofqueryexecution."
Notethoughthatthisdoesnotapplyacrossentiretransactions,asyoumayexpect.Thusatransactionlike:
STARTTRANSACTION
INSERTINTOEVENTSVALUES(NOW(),'A')
INSERTINTOEVENTSVALUES(NOW(),'B')
COMMIT
willresultinpotentiallytwodifferenttimesbeingrecordedforthetworecords.
PostedbycamerongreenonSeptember1620056:13am
[Delete][Edit]
Ifyouneedthetypetobedynamicallytakenfromatable(thatiswhereyouhave"year","day","month"etcasacolumninthetable),hereisthebestwayIcouldwork
outtodoit.Expandasnecessary:
SELECTset_date,unit_period,unit_multiplier,CASEWHENunit_period="month"THENDATE_SUB(set_date,INTERVALunit_multiplierMONTH)WHENunit_period
="week"THENDATE_SUB(set_date,INTERVAL(unit_multiplier*7)DAY)WHENunit_period="year"THENDATE_SUB(set_date,INTERVALunit_multiplierYEAR)
ELSEDATE_SUB(set_date,INTERVALunit_multiplierDAY)ENDFROMdates_table
PostedbyAndrzejSalamononSeptember2220051:27pm
[Delete][Edit]
Returnsallrowsfromactualmonthtogiven@months.eg.ifyouwantgetallrowsin:
5monthsfromnow:
(200509)5=(200504)
allrowsfrom20050401to20050430
2monthsfromnow
(200509)2=(200507)
allrowsfrom20050701to20050731
SQLvariables,canbePHPvariableslike$months,$nextMonth,$begin,$end
set@months=1#changeonlythisvalue(monthsbackfromactualmonth)
set@nextMonth=@months+1
set@begin=FROM_DAYS(TO_DAYS(LAST_DAY(DATE_SUB(NOW(),INTERVAL@nextMonthMONTH)))+1)
set@end=FROM_DAYS(TO_DAYS(LAST_DAY(DATE_SUB(NOW(),INTERVAL@monthsMONTH)))+1)
SELECTcols_u_wantFROMtbl_u_want
WHEREtimestampCol
BETWEEN@beginAND@end
It`smysolution.IfUhaveYourownpleaseemailme.
Sorryformyenglish:)
PostedbyBryanDonovanonNovember1420059:22pm
[Delete][Edit]
I'mnotsureifthisisthebestway,butitworkstogetthedateoftheMondayoftheweekofadate.Forexample,ifyouhaveadatetimecolumncalledstarttimeina
tablecalledtest_events,youcouldselectthedistinctMondaysfromyourtableasfollows:
SELECTDISTINCT(STR_TO_DATE(CONCAT(YEARWEEK(starttime),'1'),'%x%v%w'))
FROMtest_events
Hopefullythereisabetterway..
PostedbyRodolfoMaripanonNovember2920053:52pm
[Delete][Edit]
Iwasusingmysqlv4andthedatewasinavarchardatatype,inordertochangethedatatypeinmysqlv5iusethefollowingcode:
updatessd_escondida.tactual_sag4setssd_escondida.tactual_sag4.Fecha=str_to_date(ssd_escondida.tactual_sag4.Fecha2,'%e/%m/%Y')
where:
ssd_escondida:database
tactual_sag4:isatable
Fecha:isadatetype
Fecha2:isavarcharwhichcontainsadate,butisfrom01/01/2005to04/01/2005(withazeroatthebegining)
whyiused%einsteadof%d???theanswerisverysimple,thereisaproblemwithdehelpaboutstr_to_date:
%d:representsthedays,butfrom0to31and...
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
22/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
%e:representsthedays,butfrom00to31.
that'sthereasonwhywecannotuse:str_to_date('00/00/0000',%d/%m/%Y),wemustusestr_to_date('00/00/0000','%e/%m/%Y')
Anotherwayinordertochangeastringlike:00/00/0000toadateistouse:str_to_date('00/00/0000','0%d/%m/%Y')
PostedbyReginaMullenonDecember3200510:25pm
[Delete][Edit]
Simplemethodofconvertingdatesfromanyof
MMDDYYYY
MM/DD/YYYY
MM.DD.YYYY
(oldDate)toYYYYMMDD(addDate).Loaddateinastextandconvertinonegousing:
<code>
updatetablesetaddDate=CONCAT_WS('',RIGHT(oldDate,4),LEFT(oldDate,2),SUBSTRING(oldDate,4,2))
</code>
Caveat:makesureyourtextinputdoesn'thavespaces.
PostedbyHyperHackeronDecember26200510:54pm
[Delete][Edit]
InMySQL4.0,andpossiblyothers,UNIX_TIMESTAMP()doesn'tworkwithdatesbefore1970.Thisquerydoesthesame,andworkswithanydatefromfromFri,13
Dec190120:45:54toTue,19Jan203803:14:07.'date'isthenameoftheDATETIMEcolumnyouneedatimestampof.
SELECT(((TO_DAYS(date)*86400)+TIME_TO_SEC(date))(TO_DAYS("19700101")*86400))AStimestamp
Ifyou'reusingPHP,notethatdate()accountsforDSTandthusmayappeartoreturnincorrectresultsalso,don'tforgettoescapethequotesaround19700101.
PostedbyNoelAthaideonDecember2720058:23am
[Delete][Edit]
Keyphrases:Birthdayreminder,selectdatesbetween
Thismightbeuseful.Ifyouhaveadatabasecontaining'name'and'birthday'(ascolumns)thenthefollowingquerywilllistthebirthdaysinthenext15days.(16tobe
moreprecise:))
WhatIfounduniqueaboutthisproblemisthattheYEAR(ofbirth)willalwaysbedifferentandhenceonecannotsimplyuseaquerylike:
|SELECT*FROM`friends`WHERE
|`birthday`>=CURDATE()
|AND
|`birthday`<=ADDDATE(CURDATE(),INTERVAL15DAY);
becauseitwouldtaketheyearintoconsideration.
Thecorrectway,Ibelieve,togetthedesiredresultisasfollows:
|SELECT*FROM`friends`WHERE(
|EXTRACT(MONTHFROM`birthday`)=EXTRACT(MONTHFROM
|CURDATE())
|AND
|DAYOFMONTH(`birthday`)>=DAYOFMONTH(CURDATE())
|AND
|DAYOFMONTH(`birthday`)<=(DAYOFMONTH(CURDATE())+15)
|)
|
|OR(
|EXTRACT(MONTHFROM`birthday`)=EXTRACT(MONTHFROM
|ADDDATE(CURDATE(),INTERVAL15DAY))
|AND
|DAYOFMONTH(`birthday`)<=DAYOFMONTH(ADDDATE(CURDATE(),
|INTERVAL15DAY))
|)
Thelogicshouldbeclearfromthequeryitself.NotethatinoneplaceIusenumericaladdition(DAYOFMONTH(CURDATE())+15)whilelowerdownIusethe
ADDDATEfunction.Thisdistinctionisimportant.
Wouldbehappyifsomeonecouldrefinetheabovemethod.
NoelAthaide.
PS:Putthisintoascriptandcrontabit...andyouhaveasimpleBirthdayreminder:)
Postedby[namewithheld]onJanuary12200611:51pm
[Delete][Edit]
thebirthdayreminderdoesn'tworkthewayitshouldbe.Ifoundthebugandfixedit.thisisaworkingexample:
SELECTuser_birthdate,user_name,user_id,EXTRACT(MONTHFROM`user_birthdate`)month,EXTRACT(DAYFROM`user_birthdate`)day
FROM".$db_prefix."users
WHERE
(
EXTRACT(MONTHFROM`user_birthdate`)=EXTRACT(MONTHFROMCURDATE())
AND
DAYOFMONTH(`user_birthdate`)>DAYOFMONTH(CURDATE())
AND
DAYOFMONTH(`user_birthdate`)<=(DAYOFMONTH(CURDATE())+15)
)
OR
(
EXTRACT(MONTHFROMADDDATE(CURDATE(),INTERVAL15DAY))<>EXTRACT(MONTHFROMCURDATE())
AND
EXTRACT(MONTHFROM`user_birthdate`)=EXTRACT(MONTHFROMADDDATE(CURDATE(),INTERVAL15DAY))
AND
DAYOFMONTH(`user_birthdate`)<=DAYOFMONTH(ADDDATE(CURDATE(),INTERVAL15DAY))
)
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
23/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
ORDERBYmonth,day,user_idASC
sorryforthestrangename,butthisisthewaymytablearenamed...
hopeyoulikeit
PostedbyStijnTasonJanuary2320064:07pm
[Delete][Edit]
I'musingthisqueryforabirthdayreminder:
SELECT`geb_Geboorte`
FROM`gebruikers`
WHERE
DAYOFYEAR(curdate())<=dayofyear(`geb_Geboorte`)
AND
DAYOFYEAR(curdate())+15>=dayofyear(`geb_Geboorte`)
Ichangetheyearofbirthdaytothecurrentyear.
Sorryforthedutchtablenames.
PostedbyJohnL.onJanuary2520063:56pm
[Delete][Edit]
Ittookmeabitoftimetofindhowtoselectdatabasedontimeperiods(suchasforquarterlyoryearlyreports).Youcanusegroupbymonth(DateTypeColumn).
exampletofindperiodictotals:
SELECT[Year|Quarter|Month|Day](date)asPeriod,shipcountry,shipstate,shipcity,sum(products),sum(shipping),sum(tax)
FROMproductsNATURALJOINshippingNATURALJOINtax
GROUPBYPeriod,shipcountry,shipstate,shipcity
morehere
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
Isupposeyoucouldalterthestartofquarterlyperiodsbydoingsomearithmeticonthe(date),butyoumighthavetodosomeconversions.
Postedby[namewithheld]onMarch620067:32pm
[Delete][Edit]
TimearithmeticusingCURTIME()isquitewillingtotypeeverythingintointegersratherthanaddingandsubtractingseconds.Forexample,wherelog_timeisaTIME
column
SELECTlog_timeASTimeFROMcall_log
WHERElog_time>=(CURTIME()60)
willfetchallresultsfromthelast60seconds.However,
SELECTlog_timeASTimeFROMcall_log
WHERElog_time>=(CURTIME()900)
willfetchallresultsfromthelast9minutes.900isinterpreted,notas900seconds(15minutes),butas9:00.Anhouris10000(1:00:00),not3600(36:00).
Ifyouwanttoaddseconds,usesomethinglikethefollowing(forthelasthour)
SELECTlog_timeASTimeFROMcall_log
WHERElog_time>=(CURTIME()SEC_TO_TIME(3600))
PostedbyIssacGoldstandonMarch9200612:34am
[Delete][Edit]
Ifyouhaveacolumnofdatevaluesandyouwanttocomparethedayportionofthemwithtoday'sdate,takinginmindshortermonthswhichmightnotcontainallthe
datesinyourset(example,billingsystemsoranythingelsewhichneedstorunoneachrecordorrecordsetonagivendayofthemonth),youcantryoneofthese
(replacing'20020430'withthedatefieldyou'recomparing):
SELECTDATE_FORMAT(CURDATE()INTERVAL1MONTH,CONCAT('%Y%m',DAY('20020430')))+INTERVAL1MONTH
Thistendsto"rounddown"onmissingdaysforexamplefordatesendingin30,thiswilltranslatetofeb28(infebruary).
PostedbyMarkoKruustkonApril520062:19pm
[Delete][Edit]
Inreplyto"DavidBerryonSeptember1720049:08pm"
Problem:Tofindweekstartandenddatewithuserspecifiedstartoftheweekdayanduserspecifieddateforwhichtheweekistobefound.
David'ssolutiondoesnotworkwithuserspecifiedweekstartandend.Itonlyworkswithnormalweekwhichis1and7asstartandendcorrespondingly.
AsIneededdifferentstartingdayforweekthanSundayorMondayfortimesheetcalculations,Ihadtocomeupwithworkingsolution:
...
date_sub(t.date,intervalif(dayofweek(t.date)$weekStartingDay>=0,dayofweek(t.date)$weekStartingDay,dayofweek(t.date)$weekStartingDay+7)day)week_start
...
date_sub(t.date,intervalif(dayofweek(t.date)$weekStartingDay>=0,dayofweek(t.date)$weekStartingDay,dayofweek(t.date)$weekStartingDay+7)6day)
week_end
...
Thissolutionworksfineforme,atleastatthemomenttillIfindsomebuginit:)
Postedby[namewithheld]onApril1420063:57am
[Delete][Edit]
UsethistofindthedateofthelastFriday.Pleaseletmeknowifthereisamoreefficientwayofdoingthis.
selectif(DATE_FORMAT(curdate(),'%w')>4,date_sub(curdate(),INTERVALDATE_FORMAT(curdate(),'%w')5DAY),date_sub(curdate(),INTERVAL
DATE_FORMAT(curdate(),'%w')+2DAY))
PostedbyHorstSchirmeieronApril17200611:16pm
[Delete][Edit]
Justanotherexampleonhowtofigureouthowmanydaysareuntilsomebirthdate(inordertodoarangequery,orgetthe"next"birthday):
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
24/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
SELECTname,birthday,
IF(DAYOFYEAR(birthday)>=DAYOFYEAR(NOW()),
DAYOFYEAR(birthday)DAYOFYEAR(NOW()),
DAYOFYEAR(birthday)DAYOFYEAR(NOW())+
DAYOFYEAR(CONCAT(YEAR(NOW()),'1231')))
ASdistance
FROMbirthdates
The+DAYOFYEAR(CONCAT(YEAR(NOW()),'1231'))(whichis366or365,dependingonwhetherwe'reinaleapyearornot)takescareoftheNewYear'sEvewrap
around.
YoucouldaddWHEREdistance<=10orORDERBYdistanceASCLIMIT1attheendofthequery,forexample.
PostedbyFrederickDucharmeonMay920069:25pm
[Delete][Edit]
Asimplewaytogetthenumberofmonthbetween2date:
SELECTPERIOD_DIFF(EXTRACT(YEAR_MONTHFROMmydate1),EXTRACT(YEAR_MONTHFROMmydate2))ASmonth_interval
FROM....
PostedbyDmitryDimovonJune520067:07pm
[Delete][Edit]
Here'swhatIusedtogetasummaryofsomevaluebydayoftheweek:
selectdate_format(date,"%W")AS`Dayoftheweek`,sum(cost)
fromdaily_cost
groupby`Dayoftheweek`
orderbydate_format(date,"%w")
Output:
+++
|Dayoftheweek|sum(cost)|
+++
|Sunday|271.53|
|Monday|310.95|
|Tuesday|323.6|
|Wednesday|312.45|
|Thursday|301.76|
|Friday|294.76|
|Saturday|255.83|
+++
ToorderresultsstartingwithMonday,changethe"orderby"expressionto
orderby(date_format(date,"%w")7)%7
PostedbyJensHopponJune620061:04pm
[Delete][Edit]
LAST_DAY()withMySQL3.23
Needtoshowthe1stdayofthenextmonth?andwerehappytofindLAST_DAY()andjustthoughtaboutaddingonesingledaytoitsresult?andthendiscovered
thatyouneedMySQL4+forthat?
Usethisuglychainoffunctionstoshowthe1stdayofthenextmonthinMySQL3.23:
FROM_DAYS(TO_DAYS(CONCAT(SUBSTRING(PERIOD_ADD(DATE_FORMAT(mydate,"%y%m"),1),3,4),"01")))
YoucouldsubtractonedaytosimulateLAST_DAY()atall.
PostedbyRichardWolterinkonJuly1020067:24am
[Delete][Edit]
ImadeaStoredFunctionwhichcancovertanISO8601(20060705T13:30:00+02:00)datetoaUNIXTIMESTAMPofthecorrespondingUTCorGMTdatetime,so
youcancomparetimestampsfromdifferenttimezoneswitheachother.Hopethiscanhelpsomeone.
CREATEFUNCTIONISO8601TOUNIXTIMESTAMP(isovarchar(25))
RETURNSINTEGER(15)
DETERMINISTIC
BEGIN
DECLARECONVTIMEINTEGER(11)
SETCONVTIME=(SUBSTRING(iso,21,2)*60)+SUBSTRING(iso,24,2)
IFSUBSTRING(iso,20,1)='+'THEN
SETCONVTIME=0CONVTIME
ENDIF
RETURNUNIX_TIMESTAMP(DATE_ADD(STR_TO_DATE(CONCAT(SUBSTRING(iso,1,10),'',SUBSTRING(iso,12,8)),'%Y%m%d%H:%i:%s'),INTERVALCONVTIME
MINUTE))
END
PostedbyAzizurRahmanonJuly12200610:08am
[Delete][Edit]
Togetthefirstdayofthecurrentmonth:
SELECT((PERIOD_ADD(EXTRACT(YEAR_MONTHFROMCURDATE()),0)*100)+1)asFirstDayOfTheMonth
Thiswillgiveyouthefirstdayofthemonth.
mysql>SELECT((PERIOD_ADD(EXTRACT(YEAR_MONTHFROMCURDATE()),0)*100)+1)asFirstDayOfTheMonth
++
|FirstDayOfTheMonth|
++
|20060701|
++
1rowinset
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
25/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
Togetthelastdayofthecurrentmonth:
SELECT(SUBDATE(ADDDATE(CURDATE(),INTERVAL1MONTH),INTERVALDAYOFMONTH(CURDATE())DAY))ASLastDayOfTheMonth
Thiswillgiveyouthefirstdayofthemonth.
mysql>SELECT(SUBDATE(ADDDATE(CURDATE(),INTERVAL1MONTH),INTERVALDAYOFMONTH(CURDATE())DAY))ASLastDayOfTheMonth
++
|LastDayOfTheMonth|
++
|20060731|
++
1rowinset
Hopethishelps!
PostedbyJordanGrayonAugust1200611:17am
[Delete][Edit]
Thisfunctionwillreturnthedifferencebetweentwodatesasastring,intheformat"Yyear[s],Mmonth[s],Dday[s]"(pluralisationasappropriate):
|CREATEFUNCTIONgetDateDifferenceString(date1DATE,date2DATE)RETURNSVARCHAR(30)
|RETURNCONCAT(
|/*Yearsbetween*/
|@years:=TIMESTAMPDIFF(YEAR,date1,date2),
|IF(@years=1,'year,','years,'),
|/*Monthsbetween*/
|@months:=TIMESTAMPDIFF(MONTH,DATE_ADD(date1,INTERVAL@yearsYEAR),date2),
|IF(@months=1,'month,','months,'),
|/*Daysbetween*/
|@days:=TIMESTAMPDIFF(DAY,DATE_ADD(date1,INTERVAL@years*12+@monthsMONTH),date2),
|IF(@days=1,'day','days')
|)
|;
Ittookawhiletoworkthisoneout,soIhopethismightsavesomeoneelsethebother.
PostedbyDaevidVincentonAugust420067:14am
[Delete][Edit]
I'mnotsurewhyHorstSchirmeierdidthatverycomplexbirthdateequation.Seemstomeyoucouldjustdo:
SET@DOYNOW=DAYOFYEAR(CURDATE())
SELECT(DAYOFYEAR(birthdate)@DOYNOW)ASbirthdays,birthdate,@DOYNOW,CURDATE()
FROMusers
WHEREbirthdateISNOTNULL
thenifbirthdays==0,it'sthatpersonsbirthday,otherwiseyouknowifthebirthdayisinthefuturebyhowmanydays,orifyoumisseditandhowmanybeersyouowe
them...
(althoughthemissed/negativedaysseemstobeoff)
+++++
|birthdays|birthdate|@DOYNOW|CURDATE()|
+++++
|83|19691026|216|20060804|
|3|19810807|216|20060804|
|1|19720802|216|20060804|
|0|19460804|216|20060804|
|151|19760305|216|20060804|
+++++
Shouldn'tthat1be2?
AmImissingsomethingobvious?
IfIdo"SELECTDATEDIFF('20060801',CURDATE())"Iget2asIexpect.
So,Iguesstherealsolutionistousethis:
SET@YEAR=CONCAT(EXTRACT(YEARFROMCURDATE()),'')
SELECTDATEDIFF(CONCAT(@YEAR,DATE_FORMAT(birthdate,'%m%d')),CURDATE())ASbirthdays,birthdate,CURDATE()
FROMusers
WHEREbirthdateISNOTNULL
++++
|birthdays|birthdate|CURDATE()|
++++
|83|19691026|20060804|
|3|19810807|20060804|
|2|19720802|20060804|
|0|19460804|20060804|
|152|19760305|20060804|
++++
Bytheway,ifyou'reusingPHPorsomeotherscriptinglanguage,youcangetridofthe@YEARstuffandjustdo:
DATEDIFF(DATE_FORMAT(birthdate,'".date('Y')."%m%d'),CURDATE())ASbirthdays
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
26/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
PostedbyArturasD.onAugust18200611:11am
[Delete][Edit]
Keyphrases:Birthdayreminder
Thisisanotherqueryforthebirthdayremainder:
|SELECT*FROM`users`
|WHERE
|(
|DAYOFYEAR(NOW())>DAYOFYEAR(DATE_SUB(birthdate,INTERVAL7DAY))
|AND
|DAYOFYEAR(NOW())<=DAYOFYEAR(DATE_SUB(birthdate,INTERVAL7DAY))+7
|)
|OR
|(
|DAYOFYEAR(NOW())>DAYOFYEAR(birthdate)7
|AND
|DAYOFYEAR(NOW())<=DAYOFYEAR(birthdate)
|);
PostedbyjeremylevineonAugust2220067:18pm
[Delete][Edit]
Getthefirstdayand/orlastdayofthecurrentyear.
Thisisthefirstdayoftheyear(simple)
SELECTMAKEDATE(EXTRACT(YEARFROMCURDATE()),1)
Thisisthelastday(notyoucannotjustreplacethe1witha365,someyearsyouneeda366)
SELECTSTR_TO_DATE(CONCAT(12,31,EXTRACT(YEARFROMCURDATE())),'%m%d%Y')
PostedbyDaveGreenonSeptember1420069:51pm
[Delete][Edit]
SERIALDATES
toconvertdatesstoredasadouble(Dateserialasusedbymicrosoftetci.e.38883.8941421412.Thewholenumberisthenumberofdayssinceeither31/12/1899or
01/01/1900,thefractionbeingtheproportionof1day)intoadd/mm/yyyyhh:mmformat:
noteMySQLrequiresthedatetakenfrom31/12/1899,andeventhentheadditionofnumberofdaysisstilloutby1becauseMySQLlikeExcelandotherprograms
incorrectlyassumesthattheyear1900wasaleapyear,whenitwasn'tforsomereason.
TheSQLtogetthecorrectdateis:
ADDDATE(ADDDATE('1899123100:00',<serialdate>),INTERVAL1DAY)
Thefractionofthetimecanbemultipliedbythenumberofsecondsinaday(84,600)andthenaddedtothedateasanumberofsecondstogetthetimeaswell,so
foradatetimetheSQLis:
ADDDATE(ADDDATE(ADDDATE('1899123100:00',<serialdate>),INTERVAL1DAY),INTERVAL(MOD(<serialdate>,1)*86400)SECOND)
Sorryisthisisabitobvious,itjusttookmeawhiletofindallthisout.Hopeithelps.
PostedbyErelSegalonNovember120064:53am
[Delete][Edit]
NotethattheorderofargumentsinTIMEDIFFisoppositethaninTIMESTAMPDIFF,so:
TIMESTAMPDIFF(SECOND,expr1,expr2)=TIME_TO_SEC(TIMEDIFF(expr2,expr1))
PostedbyAmitKondhareonNovember920067:52am
[Delete][Edit]
Noreadymadefunctionisprovidedforvalidatedate
Thisfunctionwork
(youcantakewhateversizeyouwantinvarchar(11024))
CREATEFUNCTIONIsDate(sInvarchar(1024))RETURNSINT
BEGIN
declaretpint
iflength(date(sIn))isnotnullthen
settp=0
else
settp=1
endif
RETURNtp
END
Ifyoufindanybugforthispleasepostithereasthisisnotcompletesoluctionasdaterespondarenotknown
Iwilltrytosolvethis
PostedbyRonA.onNovember1420062:39pm
[Delete][Edit]
Getdateforfirstdayofcurrentweekiffirstdayofweekismonday(SWEDEN,FRANCE,etc):
MONDAY
selectdate_sub(curdate(),INTERVALWEEKDAY(curdate())0DAY)
TUESDAY
selectdate_sub(curdate(),INTERVALWEEKDAY(curdate())1DAY)
ANDSOON...
PostedbyAntonioAngeloonJanuary1720072:12pm
[Delete][Edit]
TheISO8601weeknumberisdefinedasthenumberoftheweekcontainingthefirstThursday.
Withthisdefinition,theISOweeknumbercorrespondstoWEEK(date,3).
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
27/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
Thefollowingreturns1fortheweekbetween20031229and20040104:
|SELECT
|WEEK('20031229',3),
|WEEK('20040104',3)
PostedbyMartinMinkaonJanuary2520075:23pm
[Delete][Edit]
Icreatedthisfunctiontocalculate"workingday"differenceoftwodates.Ifyouhavetablewithlistofholidaysyoumayuncommentpartinthisfunctiontoexcludedays
ofholidaysalso.
DELIMITER$$
DROPFUNCTIONIFEXISTS`workdaydiff`$$
CREATEDEFINER=`root`@`%`FUNCTION`workdaydiff`(bdate,adate)RETURNSint(11)
DETERMINISTIC
COMMENT'workingdaydifferencefor2dates'
BEGIN
DECLAREfreedaysint
SETfreedays=0
SET@x=DATEDIFF(b,a)
IF@x<0THEN
SET@m=a
SETa=b
SETb=@m
SET@m=1
ELSE
SET@m=1
ENDIF
SET@x=abs(@x)+1
/*daysinfirstweek*/
SET@w1=WEEKDAY(a)+1
SET@wx1=8@w1
IF@w1>5THEN
SET@w1=0
ELSE
SET@w1=6@w1
ENDIF
/*daysinlastweek*/
SET@wx2=WEEKDAY(b)+1
SET@w2=@wx2
IF@w2>5THEN
SET@w2=5
ENDIF
/*summary*/
SET@weeks=(@x@wx1@wx2)/7
SET@noweekends=(@weeks*5)+@w1+@w2
/*Uncomentthisifyouwantexcludealsohollidays
SELECTcount(*)INTOfreedaysFROMhollidayWHEREd_dayBETWEENaANDbANDWEEKDAY(d_day)<5
*/
SET@result=@noweekendsfreedays
RETURN@result*@m
END$$
DELIMITER
PostedbyJemmaHusseinonJanuary3120073:28pm
[Delete][Edit]
Ifyouwanttoselectthetimedifferencebetweentwodatetimecolumnsandthefieldsmaycontaindatetimesthatareondifferentdays,youcanusethefollowingif
statement:
SELECTIF(TIME_TO_SEC(last_date)>=TIME_TO_SEC(first_date),
TIME_TO_SEC(last_date)TIME_TO_SEC(first_date),
86400+(TIME_TO_SEC(last_date)TIME_TO_SEC(first_date)))
FROMtable
Thiswillreturnthetimebetweenthelast_dateandthefirstdate,takingintoaccountthevalueswherefirst_dateandlast_dateareondifferentdays.
PostedbyWillJaspersonMay220073:58pm
[Delete][Edit]
NOTE:DateFormatcannotbeusedtoformataTimeDiffcalculation.
Example:
SELECTDATE_FORMAT(TIMEDIFF(`appointment_start`,`appointment_end`),'%H:%i:%s'))ASdurationFROMappointments
CorrectSyntax:
SELECTTIMEDIFF(`appointment_start`,`appointment_end`)ASdurationFROMappointments
(TestedonMySQL4.1.20)
Postedby[namewithheld]onMay3120075:11pm
[Delete][Edit]
Mypickonbirthdaysremainders:
selectdate_format(date,"%d/%m"),DAYOFYEAR(CURDATE()),DAYOFYEAR(date)
fromtable
whereDAYOFYEAR(date)betweenDAYOFYEAR(CURDATE())15andDAYOFYEAR(CURDATE())+15
orderbydate_format(date,"%d/%m/%Y")
GabrielRegulyhttp://ppgr.com.br
PostedbyEjectDisconJune11200710:53am
[Delete][Edit]
AsmentionedaboveSTR_TO_DATE()isavailableasofMySQL4.1.1.
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
28/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
ThisfunctioncanbeusefulifyouaregroupingrowsbyWeekofYearandthenwanttoproduceatablewith"WeekCommencing"asthepointsonyourXaxis.
Sowhatdoyoudoifyou'recodeshopisusingpre4.1?
Here'swhatIdid.Ihaveatableofeventshappeningonadatetime.Iwantedaneventcountbyweekwiththedateofthestartoftheweek,assumingtheweekstarts
Monday.
Ihaveexploitedthegroupbyfunctiontoextracttheminimumdatetimevaluewhichinmycaseisguaranteedtobeatleastoncedaily.
Thiswillnotworkifyourdataisnotbeinginjecteddaily!
select
count(*)as'count',
date_format(min(added_on),'%Y%M%d')as'weekcommencing',
date_format(added_on,'%Y%u')as'week'
from
system
where
added_on>='20070516'
groupby
week
orderby3desc
++++
|count|weekcommencing|week|
++++
|88|2007June04|200723|
|276|2007May28|200722|
|275|2007May21|200721|
|160|2007May16|200720|
++++
Hopethatsusefulforsomeone!
ImranChaudhry
PostedbyAndrewHollowayonAugust820076:01pm
[Delete][Edit]
Duetoabuginmysqlversionspriorto5.0.36,thereisaproblemwhenperformingmultipleSEC_TO_TIMEconversionsandthereareintermediatenullvalues.Itwill
turntheresultsafterthefirstnullintonullvalues.
Forexample:ifyouhaveatable(date_diff)asfollows:
|id|time1|time2|
++++
|1|9:30:05|(null)|
|2|10:05:07|10:05:17|
|3|11:00:03|11:01:00|
|4|12:05:11|(null)|
andyourunaquery:
selectsec_to_time(time_to_sec(time1)time_to_sec(time2))asdifffromdate_diff
Youwillseeresultsasso:
|diff|
++
|00:00:00|
|(null)|
|(null)|
|(null)|
Andaqueryexcludingid1willresultin:
|diff|
++
|00:00:10|
|00:00:57|
|00:00:00|
Aworkaroundwouldbetouseacasestatement:
selectcasewhenisnull(time_to_sec(time1)time_to_sec(time2))thennullelsesec_to_time(time_to_sec(time1)time_to_sec(time2))endasdifffromdate_diff
Or,upgradetoamysqlversionincludingthisbugfix(#25643).
PostedbyMarcelBrouilletonAugust1620071:37pm
[Delete][Edit]
Todisplaythedateofthemondayprecedingagivenday,BryanDonovansuggestedthefollowing:
>SELECTDISTINCT(STR_TO_DATE(CONCAT(YEARWEEK(starttime),'1'),'%x%v%w'))
>FROMtest_events
Infact,youneedtobeconsistentinthetypeofweeksyouuse.TheabovewouldtellyouthattheMondayJuly162007ispartoftheweekstarting...MondayJuly9
2007!
Thiscomesfromweekdefinitionambiguities(seeWEEK()above).Topreventthis,specifythemodeonYEARWEEKtobeMondaybased:payattentiontotheextra
parametertothefunctionYEARWEEK)below
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
29/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
++
|DATE_FORMAT('20070716',"%W")|
++
|Monday|
++
++
|STR_TO_DATE(CONCAT(YEARWEEK('20070716'),'1'),'%x%v%w')|
++
|20070709|
++
++
|STR_TO_DATE(CONCAT(YEARWEEK('20070716',1),'1'),'%x%v%w')|
++
|20070716|
++
Onewouldexpectthatdefault_week_formathasthesameeffectonWEEKDAY()thanithasonWEEK()andthatsettingthisvariableto1or3wouldsuffice.No,asof
Mysql5.0.26itseemstohavenoeffect:
SETdefault_week_format=1
SELECTSTR_TO_DATE(CONCAT(YEARWEEK('20070716'),'1'),'%x%v%w')
++
|20070709|
++
PostedbyDaveHoldenonSeptember6200712:43am
[Delete][Edit]
ANNIVERSARIESARETRICKY!
ForversionsofMySQLpreviousto4.1itisquitedifficulttodetermineifadatefield'sanniversarydatefallswithinaspecifieddaterange.Dayofyearcalculationsfail
becauseofleapyearsandthepossibilitythatthedaterangeyouhavespecifiedspansayearboundary.HereiswhatIhavecomeupwith.Hopefullyitcansave
someonetheheadacheandGoogleFeverIhadtogothroughtocomeupwithit.
**SOMESELECTSTATEMENT...**
WHERE
((month(Date)BETWEENmonth('[MyStartDate]')ANDmonth('[MyEndDate]')
AND
month('[MyStartDate]')<=month('[MyEndDate]')
AND
(dayofmonth(Date)>=dayofmonth('[MyStartDate]')ANDmonth(Date)=month('[MyStartDate]')
OR
dayofmonth(Date)<=dayofmonth('[MyEndDate]')ANDmonth(Date)=month('[MyEndDate]')
OR
month(date)>month('[MyStartDate]')ANDmonth(date)<month('[MyEndDate]')))
OR
(
month('[MyStartDate]')>month('[MyEndDate]')
AND
(dayofmonth(Date)>=dayofmonth('[MyStartDate]')ANDmonth(Date)=month('[MyStartDate]')
OR
dayofmonth(Date)<=dayofmonth('[MyEndDate]')ANDmonth(Date)=month('[MyEndDate]')
OR
month(Date)>month('[MyStartDate]')
ORmonth(Date)<month('[MyEndDate]')
)))
PostedbyDarrenEdwardsonSeptember620076:22pm
[Delete][Edit]
IwaslookingforasolutionwhereIcouldreturnthenumberofdays,hours,Minutesandsecondsbetweentwoentriesinatable.
DATE_DIFFisnotrunningonmymysqlserverasmyproviderusesmysqlversion4.0.25
Solutionwastousetodaysandstdtimefunctionstocalculatethedifferenceinonecall.
Thefieldsstoredinthetable(report_table)are
time(00:00:00),
date(00000000)andrecord(enum)whichtellstheappthetypeoflogstored.EGstartorendofareport.
SELECT
(TO_DAYS(`end`.`date`)TO_DAYS(`start`.`date`))
(second(`end`.`time`)+(minute(`end`.`time`)*60)+(hour(`end`.`time`)*3600)
<
second(`start`.`time`)+(minute(`start`.`time`)*60)+(hour(`start`.`time`)*3600))
AS`days`,
SEC_TO_TIME(
(second(`end`.`time`)+(minute(`end`.`time`)*60)+(hour(`end`.`time`)*3600))
(second(`start`.`time`)+(minute(`start`.`time`)*60)+(hour(`start`.`time`)*3600))
)AS`hms`,
`start`.`time`as`start`,
`end`.`time`as`end`
FROM`report_table`AS`start`,`report_table`AS`end`
AND`start`.`record`='ReportBegin'
AND`end`.`record`='ReportEnd'
LIMIT1
Ifthereisnoendofreportthenitwillnotreturnaresult,asyouwouldexpect.
PostedbyRobertJaemmrichonOctober1220077:22am
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
[Delete][Edit]
30/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
Birthdayreminder
Thenextbirthday(includingtoday!)iswhenthepersonis1yearolderthanhe/shewasyesterday.SoIuse
mysql>selectname,birthday,adddate(birthday,intervaltimestampdiff(year,adddate(birthday,interval1day),current_date)+1year)asnext_bdfrompersonorderby
next_bd
++++
|name|birthday|next_bd|
++++
|FooToday|19701012|20071012|
|Bar1|19901225|20071225|
|Bar2|20000125|20080125|
|Foo|19800229|20080229|
++++
4rowsinset(0.00sec)
mysql>selectname,birthday,adddate(birthday,intervaltimestampdiff(year,adddate(birthday,interval1day),'20081012')+1year)asnext_bdfrompersonorderby
next_bd
++++
|name|birthday|next_bd|
++++
|FooToday|19701012|20081012|
|Bar1|19901225|20081225|
|Bar2|20000125|20090125|
|Foo|19800229|20090228|
++++
4rowsinset(0.00sec)
Asyoucansee,thisisalsoworkingforleapyears.
BTW:Is"20080229"plus1year"really"20090228"?)
PostedbyAaronDavidsononDecember620074:05pm
[Delete][Edit]
Totestifadateisavaliddate:
SET@testdate="20070229"
SELECTIF(@testdate=DATE_ADD(DATE_ADD(@testdate,INTERVAL1DAY),INTERVAL1DAY),TRUE,FALSE)
Returns0(false)
SET@testdate="20080229"
SELECTIF(@testdate=DATE_ADD(DATE_ADD(@testdate,INTERVAL1DAY),INTERVAL1DAY),TRUE,FALSE)
Returns1(true)
PostedbyMohamedInfiyazZafferKhalidonDecember1220071:45pm
[Delete][Edit]
Findingadatebeforeagivennumberofdays
Often,forcertainapplications,weneedtosubtractsomedaysfromagivendatetofindanotherdate.Forexample,inalibrary,weneedtogo21daysbehindfromthe
currentdateandlistthebooksthatweretakenbeforethatdate.Thiswouldbetheoverduelist.
HereisasimpleSQLstatement.Thistypeofuseispracticallyessentialtomostapps.
SELECTSUBDATE('20071212',INTERVAL3DAY)
Thelineabovewillgivetheanswer2007129.Toexplainitfurther,thefunctionSUBDATEreturnsadateaftersubtractingaspecifiedduration.Inourexample,the
durationis3days.ToindicatethatwearedealingwithDAYS,weusethetermINTERVAL.Sothefunctionabovecanbeexplainedaswhatisthedate,threedays
beforetoday?
Nowifyouwanttofindthedate20daysbeforeTODAYorthecurrentsystemdate,thisiswhatyoushoulddo:
SELECTSUBDATE(CURRENT_DATE,INTERVAL20DAY)
Inthestatementabove,weareusingoneoftheMySQLconstantsthatholdthecurrentdateontheserver.Wecount20daysbackandgettheanswerasaresult.
Happycoding.
Khalid(itsols)
PostedbyMarcusMatosonJanuary820081:02pm
[Delete][Edit]
Important:ItshouldbeknownthatMySQL>=5.0.42silentlychangesthebehaviorofcomparingaDATEcolumntoNOW().
See:http://bugs.mysql.com/bug.php?id=28929
ThisbreaksmanythingssincenowqueriesusingWHEREdatecol=NOW()willreturnNULLwherepreviouslyitwouldreturnresults.
UseCURDATE()instead.I'mhavingtogobackthroughyearsofcodetofixthis.
PostedbyTomaszKopeconJanuary1720081:41pm
[Delete][Edit]
referingtothedocumentsectiontellingaboutintervalsindate_add/date_subfunctionsdescribingexample:
SELECTDATE_ADD('19990101',INTERVAL6/4HOUR_MINUTE)
Onecanavoidfallingintotrapsimplyenclosinginterval6/4intoquotationmarkssothequerywillbelooklikethis:
SELECTDATE_ADD('19990101',INTERVAL'6/4'HOUR_MINUTE)
Thiscasetheintervalwillbeconsideredasregularstringandnocalculationwillbeperformedbeforepassingasargument
PostedbyMohamedMahironJanuary2320086:31am
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
[Delete][Edit]
31/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
EarlierIusedtimediffinwhereclauseworkedperfectlybutdon'tknowwhyitisnotworkingnowespeciallyaftercpuusageexceedsin*intwodifferentsharedhosting*
querylike
select*fromtablewheretimediff(sysdate(),datetimecolumn)<25
thisgetsrowsoflast24hours.
PostedbyPhillPaffordonMay1520083:02pm
[Delete][Edit]
IFyouneedtorunamonthlyreportfromthe1stofeachmonthwiththepreviousmonthdate,youcouldusethecasestatementbelow.
SELECTCASE
WHENMONTH(CURDATE())=01
THENSUBDATE(CURDATE(),INTERVAL31DAY)/*Dec*/
WHENMONTH(CURDATE())=02
THENSUBDATE(CURDATE(),INTERVAL31DAY)/*Jan*/
WHENMONTH(CURDATE())=03AND(YEAR(CURDATE())%4=0)
THENSUBDATE(CURDATE(),INTERVAL29DAY)/*FebLeapYear*/
WHENMONTH(CURDATE())=03AND(YEAR(CURDATE())%4!=0)
THENSUBDATE(CURDATE(),INTERVAL28DAY)/*Feb*/
WHENMONTH(CURDATE())=04
THENSUBDATE(CURDATE(),INTERVAL31DAY)/*Mar*/
WHENMONTH(CURDATE())=05
THENSUBDATE(CURDATE(),INTERVAL30DAY)/*Apr*/
WHENMONTH(CURDATE())=06
THENSUBDATE(CURDATE(),INTERVAL31DAY)/*May*/
WHENMONTH(CURDATE())=07
THENSUBDATE(CURDATE(),INTERVAL30DAY)/*Jun*/
WHENMONTH(CURDATE())=08
THENSUBDATE(CURDATE(),INTERVAL31DAY)/*Jul*/
WHENMONTH(CURDATE())=09
THENSUBDATE(CURDATE(),INTERVAL31DAY)/*Aug*/
WHENMONTH(CURDATE())=10
THENSUBDATE(CURDATE(),INTERVAL30DAY)/*Sep*/
WHENMONTH(CURDATE())=11
THENSUBDATE(CURDATE(),INTERVAL31DAY)/*Oct*/
WHENMONTH(CURDATE())=12
THENSUBDATE(CURDATE(),INTERVAL30DAY)/*Nov*/
ELSESUBDATE(CURDATE(),INTERVAL30DAY)/*Defaultsto30days*/
END
Shouldreturn'YYYYMMDD'fromdayandintervalyouruniton.
Example:
ifthedateisJan1st2008thecasewillreturn'20071201'
Addedthistogetthe1stofthemonthwhenyourunfromanydayofthemonth
SELECTCASE
WHENMONTH(CURDATE())=01
THENSUBDATE(CURDATE(),INTERVAL(31(DAYOFMONTH(CURDATE())+1))DAY)/*Dec*/
WHENMONTH(CURDATE())=02
THENSUBDATE(CURDATE(),INTERVAL(31(DAYOFMONTH(CURDATE())+1))DAY)/*Jan*/
WHENMONTH(CURDATE())=03AND(YEAR(CURDATE())%4=0)
THENSUBDATE(CURDATE(),INTERVAL(29(DAYOFMONTH(CURDATE())+1))DAY)/*FebLeapYear*/
WHENMONTH(CURDATE())=03AND(YEAR(CURDATE())%4!=0)
THENSUBDATE(CURDATE(),INTERVAL(28(DAYOFMONTH(CURDATE())+1))DAY)/*Feb*/
WHENMONTH(CURDATE())=04
THENSUBDATE(CURDATE(),INTERVAL(31(DAYOFMONTH(CURDATE())+1))DAY)/*Mar*/
WHENMONTH(CURDATE())=05
THENSUBDATE(CURDATE(),INTERVAL(30(DAYOFMONTH(CURDATE())+1))DAY)/*Apr*/
WHENMONTH(CURDATE())=06
THENSUBDATE(CURDATE(),INTERVAL(31(DAYOFMONTH(CURDATE())+1))DAY)/*May*/
WHENMONTH(CURDATE())=07
THENSUBDATE(CURDATE(),INTERVAL(30(DAYOFMONTH(CURDATE())+1))DAY)/*Jun*/
WHENMONTH(CURDATE())=08
THENSUBDATE(CURDATE(),INTERVAL(31(DAYOFMONTH(CURDATE())+1))DAY)/*Jul*/
WHENMONTH(CURDATE())=09
THENSUBDATE(CURDATE(),INTERVAL(31(DAYOFMONTH(CURDATE())+1))DAY)/*Aug*/
WHENMONTH(CURDATE())=10
THENSUBDATE(CURDATE(),INTERVAL(30(DAYOFMONTH(CURDATE())+1))DAY)/*Sep*/
WHENMONTH(CURDATE())=11
THENSUBDATE(CURDATE(),INTERVAL(31(DAYOFMONTH(CURDATE())+1))DAY)/*Oct*/
WHENMONTH(CURDATE())=12
THENSUBDATE(CURDATE(),INTERVAL(30(DAYOFMONTH(CURDATE())+1))DAY)/*Nov*/
ELSESUBDATE(CURDATE(),INTERVAL(30(DAYOFMONTH(CURDATE())+1))DAY)/*Defaultsto30days*/
END
PostedbyThomasSchferonMarch420082:41pm
[Delete][Edit]
Titel:UrlaubstageimlaufendenKalenderjahranhandeinesArbeitstagemodellsberechnen
Variablen$workable[FirstSeventh]bool1=Arbeitstag,0=KeinArbeitstag
$query="
SELECT
SUM(effectiveworkdays(vrs.confirmed_from,vrs.confirmed_to,$workableFirst,$workableSecond,$workableThird,$workableFourth,$workableFifth,$workableSixth,
$workableSeventh))ASsum
FROMapp_vacation_responsesvrs
LEFTJOINapp_vacation_requestsvrqONvrs.request_id=vrq.vacation_id
WHEREvrq.requested_by=".$employee_id."
ANDvrs.confirmed_from>='".date('Y')."0101'
ANDvrs.confirmed_to<='".date('Y')."1231'
ANDvrs.state=1
groupbyvrq.requested_by
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
32/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
"
DELIMITER$$
DROPFUNCTIONIFEXISTS`effectiveworkdays`$$
CREATEDEFINER=`myUserName`@`myHost`FUNCTION`effectiveworkdays`(STARTDATEdate,ENDDATEdate,WORKABLE1integer,WORKABLE2integer,
WORKABLE3integer,WORKABLE4integer,WORKABLE5integer,WORKABLE6integer,WORKABLE7integer)RETURNSint(11)
DETERMINISTIC
COMMENT'effectiveworkingdayfor2dates'
BEGIN
DECLAREDAYCOUNTint
DECLAREHOLIDAYCOUNT,HOLIDAYSint
DECLARESTARTDAYSint
DECLAREENDDAYSint
SETDAYCOUNT=0
SETHOLIDAYCOUNT=0
SETHOLIDAYS=0
SETSTARTDAYS=TO_DAYS(STARTDATE)1
SETENDDAYS=TO_DAYS(ENDDATE)
IF(STARTDAYS<=ENDDAYS)THEN
WHILE(STARTDAYS<=ENDDAYS)DO
SETHOLIDAYCOUNT=0
IF(WORKABLE1=1ANDWEEKDAY(FROM_DAYS(STARTDAYS))=0)THEN
SETDAYCOUNT=DAYCOUNT+1
SELECTcount(*)INTOHOLIDAYCOUNTFROMprop_holidaysWHEREd_date=FROM_DAYS(STARTDAYS)
ENDIF
IF(WORKABLE2=1ANDWEEKDAY(FROM_DAYS(STARTDAYS))=1)THEN
SETDAYCOUNT=DAYCOUNT+1
SELECTcount(*)INTOHOLIDAYCOUNTFROMprop_holidaysWHEREd_date=FROM_DAYS(STARTDAYS)
ENDIF
IF(WORKABLE3=1ANDWEEKDAY(FROM_DAYS(STARTDAYS))=2)THEN
SETDAYCOUNT=DAYCOUNT+1
SELECTcount(*)INTOHOLIDAYCOUNTFROMprop_holidaysWHEREd_date=FROM_DAYS(STARTDAYS)
ENDIF
IF(WORKABLE4=1ANDWEEKDAY(FROM_DAYS(STARTDAYS))=3)THEN
SETDAYCOUNT=DAYCOUNT+1
SELECTcount(*)INTOHOLIDAYCOUNTFROMprop_holidaysWHEREd_date=FROM_DAYS(STARTDAYS)
ENDIF
IF(WORKABLE5=1ANDWEEKDAY(FROM_DAYS(STARTDAYS))=4)THEN
SETDAYCOUNT=DAYCOUNT+1
SELECTcount(*)INTOHOLIDAYCOUNTFROMprop_holidaysWHEREd_date=FROM_DAYS(STARTDAYS)
ENDIF
IF(WORKABLE6=1ANDWEEKDAY(FROM_DAYS(STARTDAYS))=5)THEN
SETDAYCOUNT=DAYCOUNT+1
SELECTcount(*)INTOHOLIDAYCOUNTFROMprop_holidaysWHEREd_date=FROM_DAYS(STARTDAYS)
ENDIF
IF(WORKABLE7=1ANDWEEKDAY(FROM_DAYS(STARTDAYS))=6)THEN
SETDAYCOUNT=DAYCOUNT+1
SELECTcount(*)INTOHOLIDAYCOUNTFROMprop_holidaysWHEREd_date=FROM_DAYS(STARTDAYS)
ENDIF
SETSTARTDAYS=STARTDAYS+1
SETHOLIDAYS=HOLIDAYS+HOLIDAYCOUNT
ENDWHILE
ENDIF
IF((STARTDAYS=ENDDAYS)AND(DAYCOUNT=0))THEN
SETDAYCOUNT=1
ENDIF
RETURNDAYCOUNTHOLIDAYS
END$$
DELIMITER
CREATETABLEIFNOTEXISTS`prop_holidays`(
`holiday_id`int(11)NOTNULLauto_increment,
`name`varchar(50)NOTNULL,
`d_date`dateNOTNULL,
`d_type`varchar(50)defaultNULL,
`d_subtype`varchar(50)defaultNULL,
PRIMARYKEY(`holiday_id`)
)ENGINE=MyISAM
INSERTINTO`prop_holidays`(`holiday_id`,`name`,`d_date`,`d_type`,`d_subtype`)VALUES
(35,'newYearsDay','20080101','Germany','BadenWuerttemberg'),
(36,'epiphany','20080106','Germany','BadenWuerttemberg'),
(37,'goodFriday','20080321','Germany','BadenWuerttemberg'),
(38,'easterMonday','20080324','Germany','BadenWuerttemberg'),
(39,'dayOfWork','20080501','Germany','BadenWuerttemberg'),
(40,'ascensionDay','20080512','Germany','BadenWuerttemberg'),
(41,'whitMonday','20080522','Germany','BadenWuerttemberg'),
(42,'corpusChristi','20081003','Germany','BadenWuerttemberg'),
(43,'germanUnificationDay','20081101','Germany','BadenWuerttemberg'),
(44,'allSaintsDay','20081225','Germany','BadenWuerttemberg'),
(45,'xmasDay','20081226','Germany','BadenWuerttemberg')
EXAMPLEFORSYMFONYUSERS
classVacationResponseextendsBaseVacationResponse
{
publicfunctiongetThisYearsLeaveDaysPaidByUserSum($employee_id){
$c=newCriteria()
$c>add(EmployeePeer::EMPLOYEE_ID,$this>getRequestParameter("id"))
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
33/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
$tmp=EmployeePeer::doSelect($c)
$employee=$tmp[0]
$schedule=$employee>getEmploymentContract()>getWorkSchedule()
$workableFirst=$schedule>getWorkableFirst()==1?1:0
$workableSecond=$schedule>getWorkableSecond()==1?1:0
$workableThird=$schedule>getWorkableThird()==1?1:0
$workableFourth=$schedule>getWorkableFourth()==1?1:0
$workableFifth=$schedule>getWorkableFifth()==1?1:0
$workableSixth=$schedule>getWorkableSixth()==1?1:0
$workableSeventh=$schedule>getWorkableSeventh()==1?1:0
$query="
SELECT
sum(effectiveworkdays2(vrs.confirmed_from,vrs.confirmed_to,$workableFirst,$workableSecond,$workableThird,$workableFourth,$workableFifth,$workableSixth,
$workableSeventh))ASsum
FROMapp_vacation_responsesvrs
LEFTJOINapp_vacation_requestsvrqONvrs.request_id=vrq.vacation_id
WHEREvrq.requested_by=".$employee_id."
ANDvrs.confirmed_from>='".date('Y')."0101'
ANDvrs.confirmed_to<='".date('Y')."1231'
ANDvrs.state=1
groupbyvrq.requested_by
"
$connection=Propel::getConnection()
$statement=$connection>prepareStatement($query)
$resultset=$statement>executeQuery()
$results=null
foreach($resultsetas$result){
if($result["sum"]<0)
$results=0
else
$results=$result["sum"]
}
return$results
}
}
PostedbyJyotsnaChannagirionMarch3120085:41pm
[Delete][Edit]
Ifyouwanttofindoutthedifferencebetweendatecolumnandintegercolumnyoucandolikethefollowing:
selectDATE_ADD(<col_name_DATE>,INTERVAL<col_name_INTEGER>UNIT)from<table_name>
col_name_DATE:ShouldbeDATE/DATETIMEdatatype
col_name_INTEGER:ShouldbeINTEGERdataType
UNIT:canbeMINUTE,MONTH,....
PostedbyM.H.J.onMay520083:48pm
[Delete][Edit]
ForMySQL4.1youcanusethisquerytoselectthemonthdifferencebetweentwodates,whichalsotakesintoaccounttheamountofdaysofthestartingmonthand
endingmonth.
1.Thefirstpartistheperiod_difffunctiontogetatotalamountofmonthsbetweentwodates.Then1monthissubtracted(becauseofthenexttwoparts).
2.Thesecondpartistocalculatethepartofthestartingmonth(resultsin1monthfordatesstartingonthefirstofthemonth,like01012008)
3.Thethirdpartistocalculatethepartoftheendingmonth(resultsin0fordatesstartingonthefirstofthemonth,like01022008)
PERIOD_DIFF(DATE_FORMAT(`end_date`,'%Y%m'),DATE_FORMAT(`start_date`,'%Y%m'))
1
+(TO_DAYS(LAST_DAY(`start_date`))+1TO_DAYS(DATE_FORMAT(`start_date`,'%Y%m%d')))/(TO_DAYS(LAST_DAY(`start_date`))+1to_days(DATE_FORMAT
+(DAY(`end_date`)1)/(TO_DAYS(LAST_DAY(`end_date`))+1TO_DAYS(DATE_FORMAT(`end_date`,'%Y%m01')))
PostedbyPatrickBernieronMay1020086:06pm
[Delete][Edit]
Asafeandsimplewaytocalculatetheageofsomeone/something:
CREATEFUNCTIONage(_dDATETIME)RETURNSINTEGER
COMMENT'Givenbirthdate,returnscurrentage'
RETURNYEAR(NOW())YEAR(_d)IF(DATE_FORMAT(_d,'%c%d')>DATE_FORMAT(NOW(),'%c%d'),1,0)
PostedbyAndyFugateonMay2320088:56pm
[Delete][Edit]
Iworkforapublishingcompanyandrecentlyhadarequesttoshowthemodificationdate/timeforanarticleaseitherminutesago,hoursago,yesterday,ordateoflast
modificationdependingonhowrecentlythearticlewaslastmodified.Here'sacopyofthecasestatementIusedforthis:
CASE
WHENmodified_datebetweendate_sub(now(),INTERVAL60minute)andnow()THENconcat(minute(TIMEDIFF(now(),modified_date)),'minutesago')
WHENdatediff(now(),modified_date)=1THEN'Yesterday'
WHENmodified_datebetweendate_sub(now(),INTERVAL24hour)andnow()THENconcat(hour(TIMEDIFF(NOW(),modified_date)),'hoursago')
ELSEdate_format(modified_date,'%a,%m/%d/%y')
END
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
34/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
Notethatthe"yesterday"checkoccursbeforethe"hours"check.Thisisintentionalsothathourswillonlybeshownifthemodificationoccurredduringthecurrentday.
Hopethisisusefulforsomeoneelse!
PostedbySimonStefanonJuly3120086:29am
[Delete][Edit]
Hereisaselectionforabirthdayreminderwith2daysbefore(INTERVAL2DAY):
selectid,angajat_id,data_nasterefrominfo_angajat
whereDATE_ADD(date(concat(YEAR(data_nastere),"",MONTH(NOW()),"",DAYOFMONTH(NOW()))),INTERVAL2DAY)=data_nastere
PostedbyChandruNonAugust14200811:59am
[Delete][Edit]
Tofindthestartandendofamonthyoucanusethefollowingqueries:
Lastdayofcurrentmonth:
SELECTLAST_DAY(now())
LastdayofPreviousmonth
SELECTLAST_DAY(now()interval1month)
Firstdayofcurrentmonth:
SELECTconcat(date_format(LAST_DAY(now()),'%Y%m'),'01')
Firstdayofpreviousmonth:
SELECTconcat(date_format(LAST_DAY(now()interval1month),'%Y%m'),'01')
PostedbyMatiasThayeronOctober920082:22pm
[Delete][Edit]
Hi,hereisaMySQL(5)functiontovalidateadate,informatYYYYMMDD(example:"selectisDate(20080229)").Thisfunctioninclude"leapyear"validation.
Itrytosimulate"isdate()"functionofSqlServer.
DELIMITER$$
CREATEFUNCTION`isDate`(svarchar(100))RETURNSdecimal(8)
BEGIN
/*validafechasuponiendoqueesingresadocomo"20081228"(largo8)*/
declaretpint
declarebisiestoint
sets=trim(s)
/*realizamosvalidacionesgenerales*/
iftrim(s)=0andlength(trim(s))<>8then
return0/*fechainvalida*/
endif
ifsubstr(s,1,4)notbetween0and9999then
return0/*annoinvalido*/
endif
ifsubstr(s,5,2)notbetween1and12then
return0/*mesinvalido*/
endif
/*vemossiesbisiestoelano*/
setbisiesto=0
ifsubstr(s,1,4)mod400=0thensetbisiesto=1
elseifsubstr(s,1,4)mod100=0thensetbisiesto=0
elseifsubstr(s,1,4)mod4=0thensetbisiesto=1
elsesetbisiesto=0
endif
settp=
(casewhensubstr(s,7,2)<=
casesubstr(s,5,2)
when'01'then31
when'02'then
casewhenbisiesto=1then29else28end/*sielannoesbisiestofebrerotiene29dias*/
when'03'then31
when'04'then30
when'05'then31
when'06'then30
when'07'then31
when'08'then31
when'09'then30
when'10'then31
when'11'then30
when'12'then31
else0end
andsubstr(s,7,2)>0
then1else0end)
returntp
END$$
PostedbyParisAlexonNovember19200812:37am
[Delete][Edit]
I'vealwaysfinditusefultobeabletofindoutthenumberofrecordscreatedonamonthlybasis.ThisSELECTstatementdoesthejobbyformattingadatefieldusing
DATE_FORMAT()andgroupittoseedatabytheyearandmonth.
SELECTDATE_FORMAT(creationDate,'%Y%m')ASmonth,COUNT(*)AStotalFROMmyTableGROUPBYmonthORDERBYtotalDESCLIMIT5
+++
|month|total|
+++
|200607|485|
|200608|179|
|200810|96|
|200806|89|
|200801|84|
+++
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
35/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
5rowsinset(0.00sec)
TheORDERBYandLIMITisoptional,tofurtherfiltertheselectstatement.
Regards,
Alex
http://www.loveromehotel.com/
PostedbyJooMarquesGomesonFebruary620093:46pm
[Delete][Edit]
Getfirstdayofcurrentweek.WhenfirstdayisaSunday:
selectdate_sub(curdate(),intervaldayofweek(curdate())1day)
Joao
PostedbyLoretoParisionFebruary8200911:44am
[Delete][Edit]
Ifoundfunctionstr_to_date()veryusefulwhenhaving"humanreadable"dateformatsandyouwanttousetheORDERBYclausetosortthetablebythosefields:
Supposedwehaveafields'published_date'likethis:
SELECT[,]published_date[,]
++
|published_date|
++
|Fri,23Jan200900:00:000800|
|Mon,26Jan200902:21:090800|
|Fri,23Jan200916:00:000800|
|Thu,22Jan200915:00:000800|
|Thu,29Jan200902:00:270800|
++
NowwetrytoORDERBYpublished_dateDESC,resultingin:
SELECT[,]published_date[,]ORDERBYpublished_dateDESC[]
++
|published_date|
++
|Wed,21Jan200918:30:000800|
|Wed,21Jan200911:30:360800|
|Tue,27Jan200900:09:460800|
|Tue,20Jan200916:00:000800|
|Tue,13Jan200916:00:000800|
++
Asyoucanseethesetisnotwellsorted,Sosimplyusethestr_to_datefunwiththesyntax:
SELECT[,]str_to_date(published_date,'%a,%d%b%Y%H:%i:%s')asmy_published_date[,]ORDERBYmy_published_dateDESC[]
Sowe'llhave:
++
|my_published_date|
++
|2009013011:39:04|
|2009012910:26:51|
|2009012902:00:27|
|2009012700:09:46|
|2009012608:10:45|
++
andthesetisnowsortedwell.
PostedbyStevenCopleyonMarch2620091:00am
[Delete][Edit]
Thiswillgiveweekdays(everythingminusweekends)between2dates:
SELECT
(floor(datediff('20090111','20090101')/7)*5)+
CASEdayofweek('20090101')
WHEN1THENmod(datediff('20090111','20090101'),7)2
WHEN7THENmod(datediff('20090111','20090101'),7)1
ELSE
LEAST(7dayofweek('20090101'),mod(datediff('20090111','20090101'),7))
END
PostedbyJoshuaLeboonMay1920097:32pm
[Delete][Edit]
Anotherwaytofindthelastdayofamonth(withoutLAST_DAY),givenadatewithinthatmonth:
selectdate_sub(concat(date_format(date_add(curdate(),interval1month),'%Y%m'),'01'),INTERVAL1DAY)
orforaspecificday:
selectdate_sub(concat(date_format(date_add('20080218',interval1month),'%Y%m'),'01'),INTERVAL1DAY)
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
36/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
walkstothefirstofthefollowingmonth,thensubtracts1day
PostedbyDanielBersteinonJune2320094:01pm
[Delete][Edit]
TofindfuturedateinXbusinessdays,tookmeawhilebuthereitiswithoutusingstoreprocedures,insteadIcomputethenumberofweekendsbetweentheinitial
dateanddate+Xdays,adjustfortheweekenddays.Itsimplementedasaderivedtabletoeasyjoinswithrealtables.
<code>
/*Theinitialdatefromwhentostartcounting*/
SET@start:=NOW()
/*Numberofbusinessdays*/
SET@days:=4
/*Thequery*/
SELECTcalendar.`Result`
FROM(
/*Ifinitialdateisonaweekend,adjusttofirstbusinessday*/
SELECT@start:=@start+INTERVALCASEWHENDAYOFWEEK(@start)=7THEN2WHENDAYOFWEEK(@start)=1THEN1ELSE0ENDDAY`First`,
@days`Days`,
/*Numberofestimatedbusinessweeks*/
@weekends:=DATEDIFF(@start+INTERVAL@daysDAY,@start)DIV5`Weekends`,
/*Estimatedtargetdatebasednumberofweekends*/
@guess:=@start+INTERVAL@days+2*@weekendsDAY`Guess`,
/*Adjustresultdateifitfallsonaweekend*/
IF(DAYOFWEEK(@guess)=1,@guess+INTERVAL1DAY,IF(DAYOFWEEK(@guess)=7,@guess+INTERVAL+2DAY,@guess))`Result`
)calendar
</code>
PostedbyMartinStjernholmonAugust320092:28pm
[Delete][Edit]
ToexpandabitonthenotebyJeffreyFriedlonOctober3120049:05am:
ThemanualstatesthatFROM_UNIXTIME(UNIX_TIMESTAMP(...))doesn'tmapbacktothesameformatteddate.Whatalsoshouldbestatedisthatthereverseisnot
trueeither.
UNIX_TIMESTAMP(ts)wheretsisaTIMESTAMPcolumnreturnstheunixtimestampstoredinitwithoutconversionto/fromaformatteddatestring.Thatavoidstrouble
withtimezonesandDSToverlapsetc.
However,whenthecolumntsissetthroughFROM_UNIXTIME(n),it(apparently)formatstheunixtimestampasastringwhichisthenparsedbacktoatimestamp
again.Theformattingandtheparsingisdonewiththesametimezone,sothetimezoneoffsetsgenerallycancelthemselvesout.Theexceptionisifthetimezoneuses
DSTandthetimestampisintheoverlappinghourinthefallwhengoingfromsummertimetonormaltime.
E.g.iftheactivetimezoneontheconnectionisCentralEuropeanTime,whichusesDST,thensetting1130630400(Sun30Oct20052:00:00CEST)through
INSERTINTOfooSETts=FROM_UNIXTIME(1130630400)
actuallysetsthetscolumnto1130634000(Sun30Oct20052:00:00CET),i.eonehourlater.
Theonlywayaroundthatproblemisapparentlytoensurethatthetimezoneusedontheconnectionisonewhichdoesn'tuseDST.E.g.UTCisareasonablechoice,
whichcanbesetontheconnectionthrough"SETtime_zone='+00:00'".
PostedbyWernerKremeronAugust420093:06pm
[Delete][Edit]
IimplementedawellknownalgorithmfromanEnglishstandardsorganisation(I'veforgottenexactlywho).
forthecalculateeastersundayiusedfollowingfunction:
DELIMITER$$
USE`pczeitdb`$$
DROPFUNCTIONIFEXISTS`fneastern`$$
CREATEDEFINER=`wkroot`@`%`FUNCTION`fneastern`(iYearINT)RETURNSDATE
DETERMINISTIC
BEGIN
SET@iD=0,@iE=0,@iQ=0,@iMonth=0,@iDay=0
SET@iD=25511*(iYear%19)
SET@iD=IF(@iD>50,(@iD21)%30+21,@iD)
SET@iD=@iDIF(@iD>48,1,0)
SET@iE=(iYear+FLOOR(iYear/4)+@iD+1)%7
SET@iQ=@iD+7@iE
IF@iQ<32THEN
SET@iMonth=3
SET@iDay=@iQ
ELSE
SET@iMonth=4
SET@iDay=@iQ31
ENDIF
RETURNSTR_TO_DATE(CONCAT(iYear,'',@iMonth,'',@iDay),'%Y%m%d')
END$$
DELIMITER
PostedbyBenShortonSeptember16200911:08am
[Delete][Edit]
BenjaminZagel'spostingongettingthelastdayofthemonthneedstweaking:itincorrectlytoldmethatthelastdayofthemonthwas28thofMarch.Thisiseasily
remediedsimplyswaptheorderie.addMonthFirst,THENsubtractaday:
ie:
SELECTDATE_FORMAT('20090316','%Y%m01')asFirst,(DATE_FORMAT('20090316','%Y%m01')+INTERVAL1MONTH)INTERVAL1DAYASLast
(Datefunctionsarenotcommutative).
PostedbyAndySchmidtonNovember720093:59pm
[Delete][Edit]
Ididn'tfindaformatvariabletooutputtheISOtimezoneoffset"+/HHMM",asrequiredforRSS,SMTPorHTTPheaders,etc.
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
37/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
ThefollowingwilloutputtheproperfullhouroffsetfromUTC:
SELECTTIME_FORMAT(NOW()UTC_TIMESTAMP(),'%H%i')AStz_offset
PostedbyJohnDoeonDecember21200911:56am
[Delete][Edit]
ThisisaSQLstatementtolistallthepeoplewhosebirthdayiscomingupinthenextcoupleofweeks,payingattentiontoyear'send:
SET@YEAR=EXTRACT(YEARFROMCURDATE())
SELECTnameFROMmytableWHEREDATEDIFF(DATE_FORMAT(birthdate,CONCAT(@YEAR,"%m%d")),CURDATE())BETWEEN0AND15OR
DATEDIFF(DATE_FORMAT(birthdate,CONCAT(@YEAR+1,"%m%d")),CURDATE())BETWEEN0AND15
PostedbyRickWellmanonJanuary520101:03am
[Delete][Edit]
MuchappreciationtoStevenCopley'spostconcerningweekdays[sincethatiswhatIwaslookingfor]butIthinkheusedthedayofweek()functionwherehemeantto
usetheweekday()functionintheLEAST()clause.i.e.
Thiswillgiveweekdays(everythingminusweekends)between2dates:
SELECT
(floor(datediff('20090111','20090101')/7)*5)+
CASEdayofweek('20090101')
WHEN1THENmod(datediff('20090111','20090101'),7)2
WHEN7THENmod(datediff('20090111','20090101'),7)1
ELSE
LEAST(7weekday('20090101'),mod(datediff('20090111','20090101'),7))
END
PostedbyRobertEiseleonJanuary1520104:15pm
[Delete][Edit]
Idiscussedthetopicofagecalculationtwoweeksbeforeonmyblog:http://www.xarg.org/2009/12/agecalculationwithmysql/
IfoundaverysmartsolutiontocalculatetheagefromaDATEvalue:
CREATEFUNCTIONgetage(BDAYDATE)
RETURNSTINYINTUNSIGNED
RETURNYEAR(FROM_DAYS(DATEDIFF(NOW(),BDAY)))
Tocalculatesomeonesnextbirthday,Iwroteasimilarfunction:
CREATEDFUNCTIONnextbday(bdayDATE)
RETURNSDATE
RETURNDATE_ADD(bday,INTERVALYEAR(FROM_DAYS(DATEDIFF(NOW(),bday)1))+1YEAR)
PostedbyMichaelCunninghamonJanuary2420104:20pm
[Delete][Edit]
Ipersonallygotstuck,tryingtofeedVBScriptdatesbackintoMySQLastheODBCDriverconvertstheMySQLdatestoVBScript'sversionautomatically.
ThisisaonelinersolutionforeveryoneusingVBScript(ASP),thatneedstofeedaVBdateintoMySQL.
Input:REQmodinanydateformatthatVBScriptunderstands(1/1/197012:00:01AM)
REQmod=year(REQmod)&""&right("0"&month(REQmod),2)&""&right("0"&day(REQmod),2)&""&right("0"&Hour(REQmod),2)&":"&right("0"&
Minute(REQmod),2)&":"&right("0"&Second(REQmod),2)
Output:REQmodwillbestrictlyinMySQLFormat(1970010100:00:01)
PostedbyD.MeaneaonMay420109:37pm
[Delete][Edit]
TwothingstokeepinmindwhenusingtheTIMESTAMPDIFFfunction:
1.Thefunctionreturnsatruncatedintegerofthespecifiedunit.ItdoesNOTusetheunittodeterminetheprecisionofthedifferencecalculation.Forexample,you
mightexpect
SELECTTIMESTAMPDIFF(MONTH,'20100331','20100430')
toreturn1,asthedifferencebetween'201003'and'201004'.However,becausethedifference(includingthedays)isnotquiteafullmonth,itreturns0,not1.
2.Inversion5.0,theunityouspecifydetermineswhetherthecalculationincludesthetimeelements.WhenusingtheYEARorMONTHunits,thefunctionusesthe
dateelements(year,monthandday)inthecomparison,butignoresthetimeelements.Forexample,
SELECTTIMESTAMPDIFF(MONTH,'2010030100:00:00','2010040100:00:00')
and
SELECTTIMESTAMPDIFF(MONTH,'2010030123:59:59','2010040100:00:00')
bothreturn1,while
SELECTTIMESTAMPDIFF(MONTH,'2010030200:00:00','2010040100:00:00')
returns0.
However,ifyouuseDAYastheunit,alldateandtimeelementsareincludedinthecalculation.Thus,
SELECTTIMESTAMPDIFF(DAY,'2010032900:00:00','2010033000:00:00')
returns1,while
SELECTTIMESTAMPDIFF(DAY,'2010032900:00:01','2010033000:00:00')
returns0.
Inversion5.1,thefunctionincludesthetimeelementsinallcalculations.(Mytestingwasdoneinversions5.0.75and5.1.30)
Thisfunctionworksfineforcalculationsonthetimepartofatimestampbutforworkingwiththedatepart,ImuchpreferusingtheYEAR,PERIOD_DIFF,orTO_DAYS
functions.
PostedbyStoob!onMay1220107:42pm
[Delete][Edit]
IfyouhaveaVARCHARcolumncalled,forexample,`Date`thatcontainsdatedata,butisnotformattedasaMySQLDATEcolumn,youcanconvertitusingMySQL's
STR_TO_DATEfunction.
Forinstance,Excelstorescanstoredateslikethis1/31/2010.MySQLusesthis,20100131.
Step1.
CreateacolumnoftypeDATEcalled`MySQLDate`
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
38/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
Step2.
UPDATE`table`SETMySQLDate=(SELECTSTR_TO_DATE(`Date`,'%c/%e/%Y'))
Alsohereisanothertip.ThereisaLAST_DAY()functionbutnoFIRST_DAY()function.ThishasthesameeffectofFIRST_DAY:itsubtractsamonth,findlastday,and
thenadd1day.
UPDATE`table`SETstart_date=DATE_ADD(LAST_DAY(DATE_SUB(start_date,INTERVAL1MONTH)),INTERVAL1DAY)
PostedbySankarRamanathanonJuly220106:50am
[Delete][Edit]
Tofindnumberofdaysinamonth.
SELECTDAY(LAST_DAY('2010021'))
or
SELECTDAYOFMONTH(LAST_DAY('20100201'))
PostedbynicolaslumbrerasonOctober520107:24pm
[Delete][Edit]
CREATEFUNCTION`workdayadd`(adate,daysint)RETURNSdate
DETERMINISTIC
COMMENT'addworkdaystodatea'
BEGIN
DECLAREfreedaysint
DECLAREdaysadd,totaldays,workday,diINT
declaredateinitdate
setdateinit=a
SETworkday=0
SETdi=DAYOFWEEK(dateinit)
settotaldays=0
WHILEworkday<=daysDO
if(di=8)then
setdi=1
endif
IF(di>1anddi<7)THEN
SETworkday=(workday+1)
ENDIF
SETdi=(di+1)
SETtotaldays=(totaldays+1)
ENDWHILE
ifdi<=2then
settotaldays=totaldaysdi
endif
setdaysadd=totaldays
whiledaysadd>0do
SELECTcount(*)INTOfreedays
FROMholliday
WHEREd_dayBETWEENdateinitANDdate_add(dateinit,intervaldaysadd1day)
ANDWEEKDAY(d_day)<5
iffreedays>0then
SETworkday=0
setdateinit=date_add(dateinit,intervaldaysaddday)
SETdi=DAYOFWEEK(dateinit)
WHILEworkday<freedaysDO
if(di=8)then
setdi=1
endif
IF(di>1anddi<7)THEN
SETworkday=(workday+1)
ENDIF
SETdi=(di+1)
SETtotaldays=(totaldays+1)
ENDWHILE
ifdi<=2then
settotaldays=totaldaysdi
endif
endif
setdaysadd=freedays
endwhile
returndate_add(a,interval(totaldays1)day)
END
PostedbyNeilHopkinsonDecember220107:36pm
[Delete][Edit]
ForthoselookingforaWEEKOFMONTHfunction:
mysql>SELECT1+WEEK(STR_TO_DATE('12/2/201011:00:00AM','%m/%d/%Y%h:%i:%s%p'))
WEEK(DATE_ADD(LAST_DAY(DATE_SUB(STR_TO_DATE('12/2/201011:00:00AM','%m/%d/%Y%h:%i:%s%p'),INTERVAL'1'MONTH)),INTERVAL'1'DAY))
FROMDUAL
>1
PostedbyJohnBurronDecember1720103:11pm
[Delete][Edit]
Tocalculatethedifferencebetweenanytwodatesortimeswhenyouwanttospecifytheunits(i.e.years,months,weeks,hours,minutes,etc.)justusethe
TIMESTAMPDIFFfunction.That'swhatwasdesignedandoptimizedtodothis.
Tocalculatetheageofalltheparticipantsinmytable,mySELECTquerylookslike:
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
39/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
SELECTname_first,name_last,TIMESTAMPDIFF(YEAR,birthdate,CURDATE())FROMparticipants
PostedbyPatrickRenaudonApril520111:04pm
[Delete][Edit]
PleasenotetheTIMEDIFFfunctionislimitedtothefollowingrange:[839h59m59s+839h59m59s].
ThesamestandsforSEC_TO_TIME.
PostedbyboblawnonApril2120112:39pm
[Delete][Edit]
FurthertoSantiBari'sexcellentsuggestionto"plugthemissinggaps",rememberthatifyouhaveadditionalclausesinyourretrieval,youmayhavetoincludealittle
extrainyoursyntax.
Forexample,followingonfromSanti'sexample,supposeyouhadafieldinthevisitstableforcapturingthebrowserused.
ToretrievethedatawherethebrowserwasFirefox,youwouldaddaWHEREclause,like:
WHEREvisits.browser='Firefox'
However,thiswillnotworkasexpected.Toplugtheholesinthedates,therightsyntaxwouldbe:
WHERE(visits.browser='Firefox'ORvisits.browserISNULL)
andthegapsinthedateswillbefilledagain!
PostedbySergKalachevonApril2220113:41am
[Delete][Edit]
UsingfunctionfromMartinMinkapostedhereonJanuary2520075:23pminthisexamplewecalculateeffectiveworkingminuteselapsedbetweencreationand
completionofServiceDeskrequest.Ihopeitmaybeuseful...
SELECT`created_at`,`finished_at`,
CASEmysql.workdaydiff(`finished_at`,`created_at`)
WHEN1THENTIMESTAMPDIFF(MINUTE,`created_at`,`finished_at`)
ELSE
(mysql.workdaydiff(`finished_at`,`created_at`)2
)*60*9+
TIMESTAMPDIFF(MINUTE,`created_at`,DATE_ADD(DATE(`created_at`),INTERVAL19HOUR))+
TIMESTAMPDIFF(MINUTE,DATE_ADD(DATE(`finished_at`),INTERVAL10HOUR),`finished_at`)
ENDASworking_time_used_to_finish_request
FROM`request`
WHERE`request_status_id`IN(4,5)
PostedbyMustaliKachwalaonApril29201111:32am
[Delete][Edit]
Anexampleondate_subtogetreportforlast7days
http://mustalikachwala.blogspot.com/2011/04/mysqlquerytogetdataforlast7days.html
PostedbyshivamsharmaonOctober3120116:51am
[Delete][Edit]
HelloAll,
Herearetwomethodstofindfirstdayofmonth:
SELECTDATE_SUB(LAST_DAY(NOW()),INTERVALDAY(LAST_DAY(NOW()))1DAY)
SELECTDATE_SUB(NOW(),INTERVALDAY(NOW())1DAY)
Hopethesewillbehelpfultoyou...:)
PostedbySANATANOJHAonFebruary220125:16pm
[Delete][Edit]
Thisissimpleexamplewrriteninsqltogetdatedifferenceinyearmonthday
CREATETABLEtemp_rent_ftth_a(
rent_uptodateDEFAULTNULL,
bill_todateDEFAULTNULL,
billyint(4)DEFAULTNULL,
billmint(2)DEFAULTNULL,
billdint(2)DEFAULTNULL,
rentyint(4)DEFAULTNULL,
rentmint(2)DEFAULTNULL,
rentdint(2)DEFAULTNULL)
insertintotemp_rent_ftth_a(rent_upto,bill_to)values('20120202','19670610')
updatetemp_rent_ftth_asetrenty=year(rent_upto),rentm=month(rent_upto),rentd=day(rent_upto)
updatetemp_rent_ftth_asetbilly=year(bill_to),billm=month(bill_to),billd=day(bill_to)
updatetemp_rent_ftth_asetrentd=rentd+30whererentd<billd
updatetemp_rent_ftth_asetrentm=rentm1whererentd30<billd
updatetemp_rent_ftth_asetrentm=rentm+12whererentm+1<billm
updatetemp_rent_ftth_asetrenty=renty1whererentm12<billm
selectrentdbilld,rentmbillm,rentybillyfromtemp_rent_ftth_a
PostedbyDenisKukharevonMay1720122:55pm
[Delete][Edit]
IfyouneedtoaccessLAST_INSERT_ID()outsideatriggerwhereithasbeenmodified,youcanuseworkaroundwithuserdefinedvariablethatistobeassignedwith
LAST_INSERT_ID()insidethetrigger.
Thisimpliesanoverheadofadditionalquerytoreadthevariable,butitseemstobetheonlywaytosolvetheproblem.
PostedbyLuisLoboBorobiaonJune8201212:04am
[Delete][Edit]
WhenyouneedtogetthetimestampofadateinacertaintimezoneorGMTtime,usethis:
select
UNIX_TIMESTAMP(
CONVERT_TZ('2012053123:59:59',
'03:00',
'+00:00'))+TIMESTAMPDIFF(second,utc_timestamp(),now())astime
ThiswillreturntheUTCtimestampforthedatetimeinArgentinaat23:59:59,GMT3.
AgenericwayofgettingtheUTCtimeofacertainLOCALDATETIMEis:
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
40/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
select
UNIX_TIMESTAMP(
CONVERT_TZ('2012053123:59:59',
substring(
replace(
concat('+',
SEC_TO_TIME(TIMESTAMPDIFF(second,utc_timestamp(),now()))
)
,'+','')
,1,6),
'+00:00'))+TIMESTAMPDIFF(second,utc_timestamp(),now())astime
PostedbyDennisGermanonJuly6201212:56am
[Delete][Edit]
Don'tuse%lformat(lowercaseL1..12)forhoursasaresultofSUBTIMEsince
selectTime_Format(SUBTIME('20:16:44','20:05:20'),'%l:%i')
resultsin12:11ratherthanthe00:11youmighthaveexpected.
PostedbyJohnLongonFebruary520132:31pm
[Delete][Edit]
JustaggregatingsomeofwhatIfoundonthispageinasinglequery.
SELECT
DAYOFLASTWEEKLASTYEAR
DATE_SUB((CURRENT_DATEINTERVAL1YEAR),INTERVALWEEKDAY((CURRENT_DATEINTERVAL1YEAR))+7DAY)LAST_YEAR_LAST_WK_MONDAY,
DATE_SUB((CURRENT_DATEINTERVAL1YEAR),INTERVALWEEKDAY((CURRENT_DATEINTERVAL1YEAR))+6DAY)LAST_YEAR_LAST_WK_TUESDAY,
DATE_SUB((CURRENT_DATEINTERVAL1YEAR),INTERVALWEEKDAY((CURRENT_DATEINTERVAL1YEAR))+5DAY)
LAST_YEAR_LAST_WK_WEDNESDAY,
DATE_SUB((CURRENT_DATEINTERVAL1YEAR),INTERVALWEEKDAY((CURRENT_DATEINTERVAL1YEAR))+4DAY)LAST_YEAR_LAST_WK_THURSDAY,
DATE_SUB((CURRENT_DATEINTERVAL1YEAR),INTERVALWEEKDAY((CURRENT_DATEINTERVAL1YEAR))+3DAY)LAST_YEAR_LAST_WK_FRIDAY,
DATE_SUB((CURRENT_DATEINTERVAL1YEAR),INTERVALWEEKDAY((CURRENT_DATEINTERVAL1YEAR))+2DAY)LAST_YEAR_LAST_WK_SATURDAY,
DATE_SUB((CURRENT_DATEINTERVAL1YEAR),INTERVALWEEKDAY((CURRENT_DATEINTERVAL1YEAR))+1DAY)LAST_YEAR_LAST_WK_SUNDAY,
DAYOFTHISWEEKLASTYEAR
DATE_SUB((CURRENT_DATEINTERVAL1YEAR),INTERVALWEEKDAY((CURRENT_DATEINTERVAL1YEAR))0DAY)LAST_YEAR_THIS_WK_MONDAY,
DATE_SUB((CURRENT_DATEINTERVAL1YEAR),INTERVALWEEKDAY((CURRENT_DATEINTERVAL1YEAR))1DAY)LAST_YEAR_THIS_WK_TUESDAY,
DATE_SUB((CURRENT_DATEINTERVAL1YEAR),INTERVALWEEKDAY((CURRENT_DATEINTERVAL1YEAR))2DAY)LAST_YEAR_THIS_WK_WEDNESDAY,
DATE_SUB((CURRENT_DATEINTERVAL1YEAR),INTERVALWEEKDAY((CURRENT_DATEINTERVAL1YEAR))3DAY)LAST_YEAR_THIS_WK_THURSDAY,
DATE_SUB((CURRENT_DATEINTERVAL1YEAR),INTERVALWEEKDAY((CURRENT_DATEINTERVAL1YEAR))4DAY)LAST_YEAR_THIS_WK_FRIDAY,
DATE_SUB((CURRENT_DATEINTERVAL1YEAR),INTERVALWEEKDAY((CURRENT_DATEINTERVAL1YEAR))5DAY)LAST_YEAR_THIS_WK_SATURDAY,
DATE_SUB((CURRENT_DATEINTERVAL1YEAR),INTERVALWEEKDAY((CURRENT_DATEINTERVAL1YEAR))6DAY)LAST_YEAR_THIS_WK_SUNDAY,
DAYOFLASTWEEKTHISYEAR
DATE_SUB(CURDATE(),INTERVALWEEKDAY(CURDATE())+7DAY)LAST_WK_MONDAY,
DATE_SUB(CURDATE(),INTERVALWEEKDAY(CURDATE())+6DAY)LAST_WK_TUESDAY,
DATE_SUB(CURDATE(),INTERVALWEEKDAY(CURDATE())+5DAY)LAST_WK_WEDNESDAY,
DATE_SUB(CURDATE(),INTERVALWEEKDAY(CURDATE())+4DAY)LAST_WK_THURSDAY,
DATE_SUB(CURDATE(),INTERVALWEEKDAY(CURDATE())+3DAY)LAST_WK_FRIDAY,
DATE_SUB(CURDATE(),INTERVALWEEKDAY(CURDATE())+2DAY)LAST_WK_SATURDAY,
DATE_SUB(CURDATE(),INTERVALWEEKDAY(CURDATE())+1DAY)LAST_WK_SUNDAY,
DAYOFCURRENTWEEKTHISYEAR
DATE_SUB(CURDATE(),INTERVALWEEKDAY(CURDATE())0DAY)CUR_WK_MONDAY,
DATE_SUB(CURDATE(),INTERVALWEEKDAY(CURDATE())1DAY)CUR_WK_TUESDAY,
DATE_SUB(CURDATE(),INTERVALWEEKDAY(CURDATE())2DAY)CUR_WK_WEDNESDAY,
DATE_SUB(CURDATE(),INTERVALWEEKDAY(CURDATE())3DAY)CUR_WK_THURSDAY,
DATE_SUB(CURDATE(),INTERVALWEEKDAY(CURDATE())4DAY)CUR_WK_FRIDAY,
DATE_SUB(CURDATE(),INTERVALWEEKDAY(CURDATE())5DAY)CUR_WK_SATURDAY,
DATE_SUB(CURDATE(),INTERVALWEEKDAY(CURDATE())6DAY)CUR_WK_SUNDAY,
DAYOFNEXTWEEKTHISYEAR
DATE_SUB(CURDATE(),INTERVALWEEKDAY(CURDATE())7DAY)NEXT_WK_MONDAY,
DATE_SUB(CURDATE(),INTERVALWEEKDAY(CURDATE())8DAY)NEXT_WK_TUESDAY,
DATE_SUB(CURDATE(),INTERVALWEEKDAY(CURDATE())9DAY)NEXT_WK_WEDNESDAY,
DATE_SUB(CURDATE(),INTERVALWEEKDAY(CURDATE())10DAY)NEXT_WK_THURSDAY,
DATE_SUB(CURDATE(),INTERVALWEEKDAY(CURDATE())11DAY)NEXT_WK_FRIDAY,
DATE_SUB(CURDATE(),INTERVALWEEKDAY(CURDATE())12DAY)NEXT_WK_SATURDAY,
DATE_SUB(CURDATE(),INTERVALWEEKDAY(CURDATE())13DAY)NEXT_WK_SUNDAY,
FIRSTANDLASTOFMONTH
DATE_FORMAT(CURRENT_DATEINTERVAL1MONTH,'%Y%m01')LAST_MON_START,
LAST_DAY(CURRENT_DATEINTERVAL1MONTH)LAST_MONTH_END,
DATE_FORMAT(CURRENT_DATE,'%Y%m01')THIS_MON_START,
LAST_DAY(SYSDATE())THIS_MONTH_END,
DATE_FORMAT(CURRENT_DATE+INTERVAL1MONTH,'%Y%m01')NEXT_MON_START,
LAST_DAY(CURRENT_DATE+INTERVAL1MONTH)NEXT_MONTH_END,
LASTYEAR,THISYEAR,NEXTYEAR
YEAR(CURRENT_DATEINTERVAL1YEAR)LAST_YEAR,
YEAR(CURRENT_DATE)CURRENT_YEAR,
YEAR(CURRENT_DATE+INTERVAL1YEAR)NEXT_YEAR,
DATE_FORMAT(CURRENT_DATE,'%Y0101')FIRST_DAY_OF_CUR_YEAR,
DATE_FORMAT(CURRENT_DATE,'%Y1231')LAST_DAY_OF_CUR_YEAR
PostedbyLyleBreweronFebruary10201310:19pm
[Delete][Edit]
Calculatingageinyearsfromdateofbirthaccuratelyusingdatediff()doesn'tworkduetoleapyears.Ifyoucalcualteaperson'sageonadateneartheirbirthday,
you'relikelytogetanincorrectresult.Theolderthesubjectis,themorelikelyyouwillgetanincorrectresultduetothenumberofleapyearsthathasoccurredina
person'slife.Forexample,apersonwhois100haslivedthroughabout25leapyears.
Calculatingageisasimpleproblem.Itboilsdowntosubtractingyearofbirthfromthecurrentyear(orwhateveryearyou'recalculatingageat)andthensubtractiing1
ifthesubject'sbirthdateisafterthethedateofthecalculationinthecalendaryearofthedateofcalculation.Forexample,ifthesubjectwasbornonJune15th,1954
andyou'recalculatingtheirageonJuly1st,1984,thentheirbirthdayhasalreadyoccurredinthecalendaryearofthedateofcalculationandthecorrectansweris
19841954=30.Thatcalculationworksifthesubject'sbirthdateisonorbeforethedateofcalculation.However,ifthatpersonwerebornonAugust1st,1954,then
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
41/42
6/12/2014
MySQL::MySQL5.0ReferenceManual::12.7DateandTimeFunctions
theirbirthdayoccurslaterinthecalendaryearthanthedateofcalculation.Inthatcase,thepersonisstillonly29onJuly1stwhichmeansthatthecorrectcaclulationis
198419541=29.
Tocalculateageinyearsaccurately,youneedacalculationwhichsimplysubtractstheyearofthedateofbirthfromtheyearofthedateofcalculationandthenadds
"1"tothecalculationiftheperson'sbirthdayoccursafterthedateofcalculationinthecalenderyearofthedateofcalculation.Iwasabletogeta100%correct
answerusinganestedifthenelsefunction.However,thesimplestapproachI'vecomeacrossisactuallyinthisreferencemanualhere:
http://dev.mysql.com/doc/refman/5.5/en/datecalculations.html
Itdoesthesamethingasmymorecomplicatedifthenelseapproachbutit'salotsimpler.Stayawayfromthedatediff()approachesforcalculatingage.Thisapproach
is100%accurate.Itwillevengiveyouthecorrectage,inyears,forsomeonebornonFebruary29th.
PostedbyLyleBreweronFebruary1220136:59pm
[Delete][Edit]
PaulDuboisofOracleemailedmewiththefollowingcomment:
Ifyou'redoingagecalculations,wouldn'tyoubebetteroffusing
TIMESTAMPDIFF(YEAR,date1,date2)?
Itrieditanditworkslikeacharm.Itestedanagecalculationagainsttoday'sdate,20130212,usingthebirthdates19110212(birthdaytoday)and19110213
(birhtdaytomorrow).Itreturnedthecorrectresultsof102for19110212(birthdaytoday)and101for19110213(birthdaytomorrow).
PostedbyALEXANDERSKAKUNOVonMarch21201312:21pm
[Delete][Edit]
Ifyouhaveaqueueandyouwanttofindouttheaveragetimeinwhichanitemgetsprocessed,youcanusethissnippet(that'swhatweuseforadashboardinour
http://yasno.tv/project).
Ifyouhaveatableofqueueditemswith`created_at`and`updated_at`datetimefieldsthatrepresentwhenanitemwasaddedandwhenitwasupdated(processed)
accordingly.So,
[code]
SELECTSEC_TO_TIME(AVG(TIME_TO_SEC(TIMEDIFF(`updated_at`,`created_at`))))ASaverage_item_time
FROM`mail_queue_item`
[/code]
showssomethinglike"00:02:30"whichmeansaverageidletimeis2.5minutesperitem.
PostedbyProgrammerOldonApril1620135:05pm
[Delete][Edit]
Inourdatabasetherearepartialdates.InspiteofALLOW_INVALID_DATESfunctionDATEDIFFyieldsNULLonthem.Therefore,Iwrotethisfunction:
CREATEFUNCTIONddiff(laitDATE,earlieDATE)RETURNSINTEGER(7)
COMMENT'lesspickiedaitdifferens'
DETERMINISTIC
RETURNROUND(PERIOD_DIFF(EXTRACT(YEAR_MONTHFROMlait),EXTRACT(YEAR_MONTHFROMearlie))*30.44)+DAY(lait)DAY(earlie)
Itisatmost2daysofftherealdifference,andthegreatlybiassedvalueforDAY(d)=0isoflittleimportanceinourcase.Ifitmattered,wewouldmakeit15.
PostedbyRickJamesonNovember2720136:52am
[Delete][Edit]
WhendidMySQLrestart?
SELECTNOW()INTERVALVARIABLE_VALUESECOND
FROMinformation_schema.GLOBAL_STATUS
WHEREVARIABLE_NAME='UPTIME'
>2013111610:07:47
Or,simplythedate:
SELECTDATE(NOW()INTERVALVARIABLE_VALUESECOND)ASStartDate
FROMinformation_schema.GLOBAL_STATUS
WHEREVARIABLE_NAME='UPTIME'
>20131116
PostedbyChrisWilsononAugust1520143:24pm
[Delete][Edit]
ThequerycachecancauseCONVERT_TZtoreturninvalidresults(NULL)evenafterthetimezonedatahasbeenloaded,becauseloadingthesetablesdoesnot
properlyinvalidatethecache.http://bugs.mysql.com/73604.
Addyourowncomment
Top/Previous/Next/Up/TableofContents
2014,OracleCorporationand/oritsaffiliates
http://dev.mysql.com/doc/refman/5.0/en/dateandtimefunctions.html
42/42