Working with Dates in PL/SQL (date used in PL/SQL)

Source: Internet
Author: User
Tags time zones

Working with Dates in PL/SQL (date used in PL/SQL) The previous articles in this introductory PL/SQL series focused on working with strings and numbers in PL/SQL-based applications. without a doubt, strings and numbers are important, but it is certainly a very rare application that does not also rely on dates. you need to keep track of when events occurred, when people were born, and much more. as a result, You will quite often need to Declare variables and constants for datesUse built-in functions to display and modify date valuesPerform computations on dates A date is also a considerably more complex datatype than string or a number. it has multiple parts (year, month, day, hour, and so on), and there are getting rules about what constitutes a valid date. this article gives you all the information y Ou need in order to begin working with dates in your PL/SQL programs. dates, Time Stamps, and Intervals in PL/SQLMost applications require the storage and manipulation of dates and times. unlike strings and numbers, dates are quite complicated: not only are they highly formatted data, but there are also using rules for determining valid values and valid calculations (leap days and years, daylight sa Ving time changes, national and company holidays, date ranges, and so on ). fortunately, Oracle Database and PL/SQL provide a set of true date and time datatypes that store both date and time information in a standard internal format, and they also have an extensive set of built-in functions for manipulating the date and time. there are three PES ypes you can use to work with dates and times: DATE-T His datatype stores a date and a time, resolved to the second. it does not include the time zone. DATE is the oldest and most commonly used datatype for working with dates in Oracle applications. TIMESTAMP-Time stamps are similar to dates, but with these two key distinctions: (1) you can store and manipulate times resolved to the nearest billionth of a second (9 decimal places of precision), and (2) You can associate a time zone with a time stamp, and Oracle Database will take that time zone into account when manipulating the time stamp. INTERVAL-Whereas DATE and TIMESTAMP record a specific point in time, INTERVAL records and computes a time duration. you can specify an interval in terms of years and months, or days and seconds. listing 1 includes example variables whose declaration is based On these datatypes. code Listing 1: Declaring DATE, TIMESTAMP, and INTERVAL variables DECLARE l_today_date DATE: = SYSDATE; hour TIMESTAMP: = hour imestamp; hour timestamp with time zone: = hour imestamp; Rochelle interval1 INTERVAL YEAR) to month: = '1970-11'; l_interval2 interval day (2) to second: = '15 00:30:44 '; BEGIN null; END; Working with intervals and time stamps with ti Me zones can be very complicated; relatively few developers will need these more advanced features. this article focuses on the core DATE and TIMESTAMP types, along with the most commonly used built-in functions. choosing a datatype. with such an abundance of riches, how do you decide which of these date-and-time datatypes to use? Here are some guidelines: Use one of the TIMESTAMP types if you need to track time down to a fraction of a second. you can, in general, use TIMESTAMP in place of DATE. A time stamp that does not contain subsecond precision takes up 7 bytes of storage, just as a DATE datatype does. when your time stamp does contain subsecond data, it takes up 11 bytes of storage. use timestamp with time zone if you n Eed to keep track of the session time zone in which the data was entered. use timestamp with local time zone if you want the database to automatically convert a time between the database and session time zones. use DATE when it's necessary to maintain compatibility with an existing application written before any of the TIMESTAMP datatypes were introduced. use datatypes in your PL/SQL code that corres Pond to, or are at least compatible with, the underlying database tables. think twice, for example, before reading a TIMESTAMP value from a table into a DATE variable, because you might lose information (in this case, the fractional seconds and perhaps the time zone ). getting the current date and time. PL/SQL developers often need to retrieve and work with the current date and time. most developers Use the classic SYSDATE function, but Oracle Database now offers several functions to provide variations of this information, as shown in Table 1. function Time Zone Datatype ReturnedCURRENT_DATE Session DATECURRENT_TIMESTAMP Session timestamp with time zonelocaltimestamp Session TIMESTAMPSYSDATE Database server DATESYSTIMESTAMP Database server timestamp with time ZONETable 1: SYSDATE and other op Tions for working with the current date and time Listing 2 displays the values returned by callto SYSDATE and policimestamp. code Listing 2: callto SYSDATE and between imestamp and the returned values BEGIN DBMS_OUTPUT.put_line (SYSDATE); values (SYSTIMESTAMP); values (SYSDATE-SYSTIMESTAMP); END;/Here is output: 07-AUG-1107-AUG-11 08.46.16.20.20.00 AM-05:00-000000 000 00:00:00. 379000000 Because I have passed dates and time stamps to DBMS_OUTPUT.PUT_LINE, Oracle Database implicitly converts them to strings, using the default format masks for the database or the session (as specified by the National Language Settings NLS_DATE_FORMAT parameter ). A default installation of Oracle Database sets the default DATE format to DD-MON-YYYY. the default TIMESTAMP format Provided des both the date offset and the time zone offset. note that it is possible to perform date arithmetic: I subtract the value returned by using imestamp from the value returned by SYSDATE. the result is an interval that is very close (but not quite equal) to zero. converting dates to strings and strings to dates. as with TO_CHAR for numbers, you use another version of the TO_CHAR function to conve Rt a date or a time stamp to a string. and, again as with numbers, Oracle Database offers a large set of format elements to help you tweak that string so it appears exactly as you need it. here are some examples: Use TO_CHAR without a format mask. if you do not include a format mask, the string returned by TO_CHAR will be the same as that returned when Oracle Database performs an implicit conversi On: BEGIN DBMS_OUTPUT.put_line (TO_CHAR (SYSDATE); DBMS_OUTPUT.put_line (TO_CHAR (SYSTIMESTAMP); END; /07-AUG-1107-AUG-11 08.55.00.470000000 AM-05:00 Use TO_CHAR to display the full names of the day and the month in the date: BEGIN DBMS_OUTPUT.put_line (TO_CHAR (SYSDATE, 'day, Day, DDth Month YYYY '); END;/Sunday, 07TH August 2011 Note: The language used to display these names is determined The NLS_DATE_LANGUAGE setting, which can also be specified as the third argument in the call to TO_CHAR, as in BEGIN DBMS_OUTPUT.put_line (TO_CHAR (SYSDATE, 'day, DDth Month YYYY ', 'nls _ DATE_LANGUAGE = Spanish '); END;/Domingo, 07TH ago sto 2011 Use TO_CHAR to display the full names of both the day and the month in the date-but without all those extra spaces in the date-as-string. oracle Database, By default, pads the string with spaces to match the maximum length of the day or the month. in most situations, you don't want to include that extra text, and Oracle Database offers a format element modifier, FM, to control blank and zero padding. in the following block, I prefix the format mask with FM and remove the 0 (before 7) and extra spaces after August: BEGIN DBMS_OUTPUT.put_line (TO_CHA R (SYSDATE, 'fmday, DDth Month YYYY '); END;/Sunday, 7TH August 2011 You can also use the format mask to extract just a portion of, or information about, the date, as shown in the following examples: What quarter is it? TO_CHAR (SYSDATE, 'q') What is the day of the year (1-366) for today's date? TO_CHAR (SYSDATE, 'ddd ') What are the date and time of a DATE variable? (This is a very common requirement, because the default format mask for a date does not include the time component, which means that asking DBMS_OUTPUT.PUT_LINE to display a date leaves out the time .) BEGIN DBMS_OUTPUT.put_line (TO_CHAR (SYSDATE, 'yyyy-MM-DD HH24: MI: ss'); END; /You can also use EXTRACT to extract and return the value of a specified element of a date. for exampleWhat year is it? EXTRACT (year from sysdate) What is the day for today's date? EXTRACT (day from sysdate) To convert a string to a date, use the TO_DATE or the TO_TIMESTAMP built-in function. provide the string and Oracle Database returns a date or a time stamp, using the default format mask for the session: DECLARE l_date DATE; BEGIN l_date: = TO_DATE ('12-JAN-2011 '); END; If the string you provide does not match the default format, Oracle Database will raise an exception: D ECLARE l_date DATE; BEGIN l_date: = TO_DATE ('january 12 100'); END;/ORA-01858: a non-numeric character was found where a numeric was expected You shoshould not assume that the literal value you provide in your call to TO_DATE matches the default format. what if the format changes over time? Instead, always provide a format mask when converting strings to dates, as in l_date: = TO_DATE ('january 12 100', 'month DD yyyy'); Date truncation. use the TRUNC built-in function to truncate a date to the specified unit of measure. the most common use of TRUNC is TRUNC (date)-without any format mask specified. in this case, TRUNC simply sets the time to 00:00:00. you can also use TRUNC to easily obtain the first day in a specified period. here are some TRUNC examples: Set l_date to today's date, but with the time set to 00: 00: 00: l_date: = TRUNC (SYSDATE ); get the first day of the month for the specified date: l_date: = TRUNC (SYSDATE, 'mm'); Get the first day of the quarter for the specified date: l_date: = TRUNC (SYSDATE, 'q'); Get the first day of the year for the specified date: l_date: = TRUNC (SYSDATE, 'y'); Date arithmetic. oracle Database enables you to perform arithmetic operations on dates and time stamps in several ways: Add a numeric value to or subtract it from a date, as in SYSDATE + 7; oracle Database treats the number as the number of days. add one date to or subtract it from another, as in l_hiredate-SYSDATE. use a built-in function to "move" a date by a specified number of months or to another date in a week. here are some examples of date arithmetic with a date and a number (assume in all cases that the l_date variable has been declared as DATE): Set a local variable to tomorrow's date: rochelle Date: = SYSDATE + 1; Move back one hour: l_date: = SYSDATE-1/24; Move ahead 10 seconds: l_date: = SYSDATE + 10/(60*60*24 ); when you add one date to or subtract it from another, the result is the number of days between the two. as a result, executing this block: DECLARE l_date1 DATE: = SYSDATE; l_date2 DATE: = SYSDATE + 10; BEGIN values (l_date2-l_date1); DBMS_OUTPUT.put_line (l_date1-l_date2); END; returns the following output: 10-10 And the following function can be used to compute the age of a person, assuming that the person's correct birth date is passed as the function's only argument: create or replace function your_age (birthdate_in DATE) return numberisbegin return sysdate-birthdate_in; END your_age; oracle Database offers several built-in functions for shifting a date by the requested amount or finding a date: ADD_MONTHS-adds the specified number of months to or subtracts it from a date (or a time stamp) NEXT_DAY-returns the date of the first weekday named in the call to the functionLAST_DAY-returns the date of the last day of the month of the specified date Here are some examples that use these built-in functions: move ahead one month: l_date: = ADD_MONTHS (SYSDATE, 1); Move backward three months: l_date: = ADD_MONTHS (SYSDATE,-3); Starting with the last day of January, move ahead one month. starting from a different date, go back one month. starting with the last day of February, go back one month. listing 3 shows three different callto the ADD_MONTHS function along with the results. code Listing 3: callto ADD_MONTHS BEGIN DBMS_OUTPUT.put_line (ADD_MONTHS (TO_DATE ('31-jan-2011 ', 'dd-MON-YYYY'), 1 )); DBMS_OUTPUT.put_line (ADD_MONTHS (TO_DATE ('27-feb-2011 ', 'dd-MON-YYYY'),-1); DBMS_OUTPUT.put_line (ADD_MONTHS (TO_DATE ('28-feb-2011 ', 'dd-MON-YYYY '),-1); END; Here is the output: 28-feb-00007-jan-11 31-JAN-11 You might be surprised at the third date in Listing 3. the first date (28 February) makes perfect sense. there is no 31st day in February, so Oracle Database returns the last day of the month. the second call to ADD_MONTHS moves the date from 27 February to 27 January: exactly one month's change. but in the third call to ADD_MONTHS, Oracle Database notices that 28 February is the last day of the month, so it returns the last day of the month specified by the second argument. find the next Saturday after today's date: l_date: = NEXT_DAY (SYSDATE, 'sat '); -- orl_date: = NEXT_DAY (SYSDATE, 'saturday '); the second argument must be a day of the week in the date language of your session (specified by NLS_DATE_LANGUAGE), provided as either the full name or the abbreviation. the returned date has the same time component as the date. ------------------------------- present by dylan.
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.