SQL Working with Dates

annuncio pubblicitario
MYSQL: Date e orari
Da Link italiano:
http://www.mrwebmaster.it/mysql/gestione-date-orari_9727.html
MySQL è molto generoso in merito alla gestione di date e orari, sono infatti davvero tante
le funzioni interne che il DBMS mette a nostra disposizione per trattare con questo
particolare tipo di dato. In questa sede non è possibile passarle in rassegna una ad una,
ma ci limiteremo a vedere le più importanti e comunemente tilizzate.
Data e orario corrente
Tra queste sicuramente vanno menzionate le funzioni per l'ottenimento di data e ora
corrente: NOW(), CURDATE() e CURTIME().
Funzione Formato della risposta
NOW()
AAAA-MM-GG HH:MM:SS
CURDATE() AAAAA-MM-GG
CURTIME() HH:MM:SS
Per fare un esempio si ipotizzi di voler inserire la data corrente all'interno del campo
"data" di una tabella "calendario":
INSERT INTO calendario (data) VALUES (CURDATE())
Operazioni sulle date
Altre funzioni di grande importanza nella gestione delle date sono le funzioni per la
somma e la sottrazione del tempo. Nella tabella che segue vediamo le principali:
Funzione
DATE_ADD()
DATE_SUB()
PERIOD_ADD()
Utilizzo
DATE_ADD(data, INTERVAL espressione tipo)
DATE_SUBB(data, INTERVAL espressione tipo)
PERIOD_ADD(Periodo, Mesi)
il Periodo va espresso informato AAAAMM oppure AAMM
PERIOD_SUBB() PERIOD_SUB(Periodo1, Periodo2)
il Periodo va espresso informato AAAAMM oppure AAMM
Di seguito alcuni esempi:
Supponiamo di voler sommare 10 giorni alla data corrente:
SELECT DATE_ADD(CURDATE(),INTERVAL 10 DAYS);
Effetuiamo la sottrazione di 2 mesi da una data specifica:
SELECT DATE_SUB('2015-04-15',INTERVAL 2 MONTHS);
Aggiungiamo 7 mesi al mese di aprile 2015:
SELECT PERIOD_ADD(201504,7);
Togliamo 3 mesi al mese di gennaio 2015:
SELECT PERIOD_ADD(201501,-3);
Calcoliamo la differenza (espressa in mesi) tra il gennaio 2015 ed ottobre 2012:
SELECT PERIOD_SUB(201501,201210);
Per finire una breve precisazione: quelle viste fin qui non sono che una piccola parte delle
funzioni interne che MySQL prevede per la gestione di date e orari. Vi rimando quindi alla
documentazione ufficiale per vedere le (tante) altre funzioni che, sono certo, vi torneranno
spesso utili nello sviluppo di applicazioni pratiche.
Formattare date e orari
Altre due interessanti funzioni di MySQl sono DATE_FORMAT() e TIME_FORMAT() le quali
servono, rispettivamente, per formattare una data e un orario.
Queste due funzioni, che si comportano in modo analogo, richiedono due argomenti:
il primo è la data da formattare;
 il secondo è una stringa composta da alcuni caratteri speciali, preceduti dal simbolo
"%" la quale svolge la funzione di "modello" per la risposta.
Vediamo di seguito quali sono questi caratteri speciali:

%d - giorno del mese numerico 00…31
 %M - nome del mese January ... December
 %m - mese numerico 00 ... 12
 %H - ora 00 ... 23
 %i - minuti 00 ... 59
 %s - secondi 00 ... 59
 %Y - anno di quattro cifre
 %y - anno di due cifre
Vediamo un esempio di utilizzo di DATE_FORMAT():

SELECT DATE_FORMAT('2015-04-15 14:33:23','%d-%m-%Y alle ore %H');
La risposta prodotta da MySQL sarà:
15-04-2015 alle ore 15
Da Link in inglese:
http://www.w3schools.com/sql/sql_dates.asp
SQL Dates
The most difficult part when working with dates is to be sure that the format of the date
trying to insert, matches the format of the date column in the database.
As long as your data contains only the date portion, your queries will work as
expected. However, if a time portion is involved, it gets complicated.
Before talking about the complications of querying for dates, we will look at the
most important built-in functions for working with dates.
MySQL Date Functions
The following table lists the most important built-in date functions in MySQL:
Function
Description
NOW()
Returns the current date and time
CURDATE()
Returns the current date
CURTIME()
Returns the current time
DATE()
Extracts the date part of a date or date/time expression
EXTRACT()
Returns a single part of a date/time
DATE_ADD()
Adds a specified time interval to a date
DATE_SUB()
Subtracts a specified time interval from a date
DATEDIFF()
Returns the number of days between two dates
DATE_FORMAT()
Displays date/time data in different formats
SQL Server Date Functions
The following table lists the most important built-in date functions in SQL Server:
Function
Description
GETDATE()
Returns the current date and time
DATEPART()
Returns a single part of a date/time
DATEADD()
Adds or subtracts a specified time interval from a date
DATEDIFF()
Returns the time between two dates
CONVERT()
Displays date/time data in different formats
SQL Date Data Types
MySQL comes with the following data types for storing a date or a date/time
value in the database:
DATE - format YYYY-MM-DD
DATETIME - format: YYYY-MM-DD HH:MI:SS
TIMESTAMP - format: YYYY-MM-DD HH:MI:SS
YEAR - format YYYY or YY




SQL Server comes with the following data types for storing a date or a date/time
value in the database:
DATE - format YYYY-MM-DD
DATETIME - format: YYYY-MM-DD HH:MI:SS
SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS
TIMESTAMP - format: a unique number




Note: The date types are chosen for a column when you create a new table in
your database!
For an overview of all data types available, go to our complete Data Types
reference.
SQL Working with Dates
You can compare two dates easily if there is no time component involved!
Assume we have the following "Orders" table:
OrderId
ProductName
OrderDate
1
Geitost
2008-11-11
2
Camembert Pierrot
2008-11-09
3
Mozzarella di Giovanni
2008-11-11
4
Mascarpone Fabioli
2008-10-29
Now we want to select the records with an OrderDate of "2008-11-11" from the
table above.
We use the following SELECT statement:
SELECT * FROM Orders WHERE OrderDate='2008-11-11'
The result-set will look like this:
OrderId
ProductName
OrderDate
1
Geitost
2008-11-11
3
Mozzarella di Giovanni
2008-11-11
Now, assume that the "Orders" table looks like this (notice the time component in
the "OrderDate" column):
OrderId
ProductName
OrderDate
1
Geitost
2008-11-11 13:23:44
2
Camembert Pierrot
2008-11-09 15:45:21
3
Mozzarella di Giovanni
2008-11-11 11:12:01
4
Mascarpone Fabioli
2008-10-29 14:56:59
If we use the same SELECT statement as above:
SELECT * FROM Orders WHERE OrderDate='2008-11-11'
we will get no result! This is because the query is looking only for dates with no
time portion.
Tip: If you want to keep your queries simple and easy to maintain, do not allow
time components in your dates!
Da Reference GuideLink lista funzioni:
https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_get-format
his section describes the functions that can be used to manipulate temporal values. See Section 11.3, “Date
and Time Types”, for a description of the range of values each date and time type has and the valid formats
in which values may be specified.
Table 12.13 Date/Time Functions
Name
Description
ADDDATE()
Add time values (intervals) to a date value
ADDTIME()
Add time
CONVERT_TZ()
Convert from one timezone to another
CURDATE()
Return the current date
CURRENT_DATE(), CURRENT_DATE
Synonyms for CURDATE()
CURRENT_TIME(), CURRENT_TIME
Synonyms for CURTIME()
CURRENT_TIMESTAMP(),CURRENT_TIMESTAMP Synonyms for NOW()
CURTIME()
Return the current time
DATE_ADD()
Add time values (intervals) to a date value
DATE_FORMAT()
Format date as specified
DATE_SUB()
Subtract a time value (interval) from a date
DATE()
Extract the date part of a date or datetime expression
DATEDIFF()
Subtract two dates
DAY()
Synonym for DAYOFMONTH()
DAYNAME()
Return the name of the weekday
DAYOFMONTH()
Return the day of the month (0-31)
DAYOFWEEK()
Return the weekday index of the argument
DAYOFYEAR()
Return the day of the year (1-366)
EXTRACT()
Extract part of a date
FROM_DAYS()
Convert a day number to a date
FROM_UNIXTIME()
Format UNIX timestamp as a date
Name
Description
GET_FORMAT()
Return a date format string
HOUR()
Extract the hour
LAST_DAY
Return the last day of the month for the argument
LOCALTIME(), LOCALTIME
Synonym for NOW()
LOCALTIMESTAMP,LOCALTIMESTAMP()
Synonym for NOW()
MAKEDATE()
Create a date from the year and day of year
MAKETIME()
Create time from hour, minute, second
MICROSECOND()
Return the microseconds from argument
MINUTE()
Return the minute from the argument
MONTH()
Return the month from the date passed
MONTHNAME()
Return the name of the month
NOW()
Return the current date and time
PERIOD_ADD()
Add a period to a year-month
PERIOD_DIFF()
Return the number of months between periods
QUARTER()
Return the quarter from a date argument
SEC_TO_TIME()
Converts seconds to 'HH:MM:SS' format
SECOND()
Return the second (0-59)
STR_TO_DATE()
Convert a string to a date
SUBDATE()
Synonym for DATE_SUB() when invoked with three arguments
SUBTIME()
Subtract times
SYSDATE()
Return the time at which the function executes
TIME_FORMAT()
Format as time
TIME_TO_SEC()
Return the argument converted to seconds
TIME()
Extract the time portion of the expression passed
TIMEDIFF()
Subtract time
TIMESTAMP()
With a single argument, this function returns the date or datetime
expression; with two arguments, the sum of the arguments
Name
Description
TIMESTAMPADD()
Add an interval to a datetime expression
TIMESTAMPDIFF()
Subtract an interval from a datetime expression
TO_DAYS()
Return the date argument converted to days
TO_SECONDS()
Return the date or datetime argument converted to seconds since
Year 0
UNIX_TIMESTAMP()
Return a UNIX timestamp
UTC_DATE()
Return the current UTC date
UTC_TIME()
Return the current UTC time
UTC_TIMESTAMP()
Return the current UTC date and time
WEEK()
Return the week number
WEEKDAY()
Return the weekday index
WEEKOFYEAR()
Return the calendar week of the date (1-53)
YEAR()
Return the year
YEARWEEK()
Return the year and week
Scarica