Problem Solution Discussion Performing Validity Checking on Date or Time Subparts
10.31 Performing Validity Checking on Date or Time Subparts
10.31.1 Problem
A st ring passes a pat t ern t est as a dat e or t im e, but you want t o perform furt her checking t o m ake sure t hat it s legal.10.31.2 Solution
Break up t he value int o subpart s and perform t he appropriat e range checking on each part .10.31.3 Discussion
Pat t ern m at ching m ay not be sufficient for checking dat es or t im es. For exam ple, a value like 1947-15-19 m ay m at ch a dat e pat t ern, but if you insert t he value int o a DATE colum n, MySQL will convert it t o 0000-00-00 . I f you want t o find out t hat t he value is bad before put t ing it int o your dat abase, com bine pat t ern m at ching wit h range checking. To m ake sure t hat a dat e is legal, break out t he year, m ont h, and day values, t hen check t hat t heyre wit hin t he proper ranges. Years should be less t han 9999 MySQL represent s dat es t o an upper lim it of 9999-12-31 , m ont h values should be in t he range from 1 t o 12, and days should be in t he range from 1 t o t he num ber of days in t he m ont h. That lat t er part is t he t rickiest ; it s m ont h- dependent , and for February, it s also year- dependent because it changes for leap years. Suppose youre checking input dat es in I SO form at . Earlier, in Recipe 10.26 , w e used an is_iso_date funct ion from t he Cookbook_Ut ils.pm library file t o perform a pat t ern m at ch on a dat e st ring and break it int o com ponent values: my ref = is_iso_date val; if defined ref { val matched ISO format pattern; check its subparts using ref-[0] through ref-[2] } else { val didnt match ISO format pattern } is_iso_date ret urns undef if t he value doesnt sat isfy a pat t ern t hat m at ches I SO dat e form at . Ot herwise, it ret urns a reference t o an array cont aining t he year, m ont h, and day values. [ 5] To perform addit ional checking on t he dat e part s, pass t hem t o is_valid_date , anot her library funct ion: [ 5] The Cookbook_Ut ils.pm file also cont ains is_mmddyy_date and is_ddmmyy_date rout ines t hat m at ch dat es in U.S. or Brit ish form at and ret urn undef or a reference t o an array of dat e part s. The part s are always in year, m ont h, day order, not t he order in which t he part s appear in t he dat e st ring. valid = is_valid_date ref-[0], ref-[1], ref-[2]; Or, m ore concisely: valid = is_valid_date {ref}; is_valid_date checks t he part s of a dat e like t his: sub is_valid_date { my year, month, day = _; year must be non-negative, month and day must be positive return 0 if year 0 || month 1 || day 1; check maximum limits on individual parts return 0 if year 9999; return 0 if month 12; return 0 if day days_in_month year, month; return 1; } is_valid_date requires separat e year, m ont h, and day values, not a dat e st ring. This forces you t o break apart candidat e values int o com ponent s before invoking it , but m akes it applicable in m ore cont ext s. For exam ple, you can use it t o check dat es like 12 February 2003 by m apping t he m ont h t o it s num eric value before calling is_valid_date . Wer e is_valid_date t o t ake a st ring argum ent assum ed t o be in a given dat e form at , it would be m uch less general. is_valid_date uses a subsidiary funct ion days_in_month t o det erm ine how m any days t here are in t he m ont h represent ed by t he dat e. days_in_month requires bot h t he year and t he m ont h as argum ent s, because if t he m ont h is 2 February , t he num ber of days depends on whet her t he year is a leap year. This m eans you m ust pass a four- digit year value. Two- digit years are am biguous wit h respect t o t he cent ury, and proper leap- year t est ing is im possible, as discussed in Recipe 5.28 . The days_in_month and is_leap_year funct ions are based on t echniques t aken st raight from t here: sub is_leap_year { my year = shift; return year 4 == 0 year 100 = 0 || year 400 == 0; } sub days_in_month { my year, month = _; my day_tbl = 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31; my days = day_tbl[month-1]; add a day for Feb of leap years days++ if month == 2 is_leap_year year; return days; } To perform validit y checking on t im e values, a sim ilar procedure can be used, alt hough t he ranges for t he subpart s are different : 0 t o 24 for t he hour, and 0 t o 59 for t he m inut e and second. Here is a funct ion is_24hr_time t hat checks for values in 24- hour form at : sub is_24hr_time { my s = shift; return undef unless s =~ \d{1,2}\D\d{2}\D\d{2}; return [ 1, 2, 3 ]; return hour, minute, second } The following is_ampm_time funct ion looks for t im es in 12- hour form at wit h an opt ional AM or PM suffix, convert ing PM t im es t o 24- hour values: sub is_ampm_time { my s = shift; return undef unless s =~ \d{1,2}\D\d{2}\D\d{2}?:\sAM|PM?i; my hour, min, sec = 1, 2, 3; hour += 12 if defined 4 uc 4 eq PM; return [ hour, min, sec ]; return hour, minute, second } Bot h funct ions ret urn undef for values t hat dont m at ch t he pat t ern. Ot herwise, t hey ret urn a reference t o a t hree-elem ent array cont aining t he hour, m inut e, and second values.10.32 Writing Date-Processing Utilities
Parts
» O'Reilly-MySQL.Cookbook.eBook-iNTENSiTY. 4810KB Mar 29 2010 05:03:43 AM
» Introduction Using the mysql Client Program
» Problem Solution Discussion Setting Up a MySQL User Account
» Problem Solution Discussion Starting and Terminating mysql
» Problem Solution Discussion Specifying Connection Parameters by Using Option Files
» Problem Solution Discussion Mixing Command-Line and Option File Parameters
» Problem Solution Discussion What to Do if mysql Cannot Be Found
» Problem Solution Discussion Setting Environment Variables
» Problem Solution Discussion Repeating and Editing Queries
» Problem Solution Discussion Preventing Query Output from Scrolling off the Screen
» Problem Solution Discussion Specifying Arbitrary Output Column Delimiters
» Problem Solution Discussion Logging Interactive mysql Sessions
» Discussion Using mysql as a Calculator
» Writing Shell Scripts Under Unix
» Writing Shell Scripts Under Windows
» MySQL Client Application Programming Interfaces
» Perl Connecting to the MySQL Server, Selecting a Database, and Disconnecting
» PHP Connecting to the MySQL Server, Selecting a Database, and Disconnecting
» Python Connecting to the MySQL Server, Selecting a Database, and Disconnecting
» Java Connecting to the MySQL Server, Selecting a Database, and Disconnecting
» Problem Solution Discussion Checking for Errors
» Python Java Checking for Errors
» Problem Solution Discussion Writing Library Files
» Python Writing Library Files
» SQL Statement Categories Issuing Queries and Retrieving Results
» Perl Issuing Queries and Retrieving Results
» Python Issuing Queries and Retrieving Results
» Java Issuing Queries and Retrieving Results
» Problem Solution Discussion Moving Around Within a Result Set
» Problem Solution Discussion Using Prepared Statements and Placeholders in Queries
» Perl Using Prepared Statements and Placeholders in Queries
» PHP Python Java Using Prepared Statements and Placeholders in Queries
» Problem Solution Discussion Including Special Characters and NULL Values in Queries
» Perl Including Special Characters and NULL Values in Queries
» PHP Including Special Characters and NULL Values in Queries
» Python Java Including Special Characters and NULL Values in Queries
» PHP Python Java Handling NULL Values in Result Sets
» Problem Solution Discussion Writing an Object-Oriented MySQL Interface for PHP
» Class Overview Writing an Object-Oriented MySQL Interface for PHP
» Connecting and Disconnecting Writing an Object-Oriented MySQL Interface for PHP
» Error Handling Issuing Queries and Processing the Results
» Quoting and Placeholder Support
» Problem Solution Discussion Ways of Obtaining Connection Parameters
» Getting Parameters from the Command Line
» Getting Parameters from Option Files
» Conclusion and Words of Advice
» Problem Solution Discussion Avoiding Output Column Order Problems When Writing Programs
» Problem Solution Discussion Using Column Aliases to Make Programs Easier to Write
» Problem Solution Discussion Selecting a Result Set into an Existing Table
» Problem Solution Discussion Creating a Destination Table on the Fly from a Result Set
» Problem Solution Discussion Moving Records Between Tables Safely
» Problem Solution Discussion Cloning a Table Exactly
» Problem Solution Discussion Generating Unique Table Names
» Problem Solution Discussion Using TIMESTAMP Values
» Problem Solution Discussion Using ORDER BY to Sort Query Results
» Solution Discussion Working with Per-Group and Overall Summary Values Simultaneously
» Problem Solution Discussion Changing a Column Definition or Name
» Problem Solution Discussion Changing a Table Type
» Problem Solution Discussion Adding Indexes
» Introduction Obtaining and Using Metadata
» Problem Solution Discussion Perl PHP
» Problem Solution Discussion Perl
» PHP Obtaining Result Set Metadata
» Python Obtaining Result Set Metadata
» Java Obtaining Result Set Metadata
» Using Result Set Metadata to Get Table Structure
» Problem Solution Discussion Database-Independent Methods of Obtaining Table Information
» Problem Solution Discussion Displaying Column Lists Interactive Record Editing
» Mapping Column Types onto Web Page Elements Adding Elements to ENUM or SET Column Definitions
» Selecting All Except Certain Columns
» Problem Solution Discussion Listing Tables and Databases
» Problem Solution Writing Applications That Adapt to the MySQL Server Version
» Discussion Writing Applications That Adapt to the MySQL Server Version
» Problem Solution Discussion Determining Which Table Types the Server Supports
» General Import and Export Issues
» Problem Solution Discussion Importing Data with LOAD DATA and mysqlimport
» Problem Solution Discussion Specifying the Datafile Location
» Problem Solution Discussion Specifying the Datafile Format
» Problem Solution Discussion Dealing with Quotes and Special Characters
» Problem Solution Discussion Handling Duplicate Index Values
» Problem Solution Discussion Getting LOAD DATA to Cough Up More Information
» Problem Solution Discussion Dont Assume LOAD DATA Knows More than It Does
» Problem Solution Discussion Skipping Datafile Columns
» Problem Solution Discussion Exporting Query Results from MySQL
» Using the mysql Client to Export Data
» Problem Solution Discussion Exporting Tables as Raw Data
» Problem Solution Discussion Exporting Table Contents or Definitions in SQL Format
» Problem Solution Discussion Copying Tables or Databases to Another Server
» Problem Solution Discussion Writing Your Own Export Programs
» Problem Solution Discussion Converting Datafiles from One Format to Another
» Problem Solution Discussion Extracting and Rearranging Datafile Columns
» Problem Solution Discussion Validating and Transforming Data
» Writing an Input-Processing Loop Putting Common Tests in Libraries
» Problem Solution Discussion Validation by Pattern Matching
» Problem Solution Discussion Using Patterns to Match Numeric Values
» Problem Solution Discussion Using Patterns to Match Dates or Times
» See Also Using Patterns to Match Dates or Times
» Problem Solution Discussion Using Patterns to Match Email Addresses and URLs
» Problem Solution Discussion Validation Using Table Metadata
» Problem Solution Discussion Issue Individual Queries Construct a Hash from the Entire Lookup Table
» Use a Hash as a Cache of Already-Seen Lookup Values
» Problem Solution Discussion Converting Two-Digit Year Values to Four-Digit Form
» Problem Solution Discussion Performing Validity Checking on Date or Time Subparts
» Problem Solution Discussion Writing Date-Processing Utilities
» Problem Solution Discussion Performing Date Conversion Using SQL
» Problem Solution Discussion Guessing Table Structure from a Datafile
» Problem Solution Discussion A LOAD DATA Diagnostic Utility
» Problem Solution Discussion Exchanging Data Between MySQL and Microsoft Access
» Problem Solution Discussion Exchanging Data Between MySQL and Microsoft Excel
» Problem Solution Discussion Exchanging Data Between MySQL and FileMaker Pro
» Problem Solution Discussion Importing XML into MySQL
» Epilog Importing and Exporting Data
» Introduction Generating and Using Sequences
» Problem Solution Discussion Using AUTO_INCREMENT To Set Up a Sequence Column
» Problem Solution Discussion Choosing the Type for a Sequence Column
» Problem Solution Discussion Ensuring That Rows Are Renumbered in a Particular Order
» Problem Solution Discussion Managing Multiple Simultaneous AUTO_INCREMENT Values
» Problem Solution Discussion Using AUTO_INCREMENT Values to Relate Tables
» Problem Solution Discussion Generating Repeating Sequences
» Problem Solution Discussion See Also
» Performing a Related-Table Update Using Table Replacement
» Performing a Related-Table Update by Writing a Program
» Performing a Multiple-Table Delete by Writing a Program
» Problem Solution Discussion Dealing with Duplicates at Record-Creation Time
» Problem Solution Discussion Using Transactions in Perl Programs
» Problem Solution Discussion Using Transactions in Java Programs
» Problem Solution Discussion Using Alternatives to Transactions
» Grouping Statements Using Locks
» Rewriting Queries to Avoid Transactions
» Introduction Introduction to MySQL on the Web
» Problem Solution Discussion Basic Web Page Generation
» Problem Solution Discussion Using Apache to Run Web Scripts
» Problem Solution Discussion Using Tomcat to Run Web Scripts
» Installing the mcb Application
» Installing the JSTL Distribution
» Problem Solution Discussion Encoding Special Characters in Web Output
» General Encoding Principles Encoding Special Characters in Web Output
» Encoding Special Characters Using Web APIs
» Introduction Incorporating Query Results into Web Pages
» Problem Solution Discussion Creating a Navigation Index from Database Content
» Creating a Multiple-Page Navigation Index
» Problem Solution Discussion Storing Images or Other Binary Data
» Storing Images with LOAD_FILE Storing Images Using a Script
» Problem Solution Discussion Retrieving Images or Other Binary Data
» Problem Solution Discussion Serving Banner Ads
» Problem Solution Discussion Serving Query Results for Download
» Introduction Processing Web Input with MySQL
» Problem Solution Discussion Creating Forms in Scripts
» Problem Solution Discussion Creating Multiple-Pick Form Elements from Database Content
» Problem Solution Discussion Loading a Database Record into a Form
» Problem Solution Discussion Collecting Web Input
» Web Input Extraction Conventions Perl
» Problem Solution Discussion Validating Web Input
» Problem Solution Discussion Using Web Input to Construct Queries
» Problem Solution Discussion Processing File Uploads
» Perl Processing File Uploads
» Problem Solution Discussion Performing Searches and Presenting the Results
» Problem Solution Discussion Generating Previous-Page and Next-Page Links
» Paged Displays with Previous-Page and Next-Page Links
» Paged Displays with Links to Each Page
» Problem Solution Discussion Web Page Access Counting
» Problem Solution Discussion Web Page Access Logging
» Problem Solution Discussion Setting Up Database Logging
» Other Logging Issues Using MySQL for Apache Logging
» Session Management Issues Introduction
» Problem Solution Discussion Installing Apache::Session
» The Apache::Session Interface
» A Sample Application Using MySQL-Based Sessions in Perl Applications
» Problem Solution Discussion The PHP 4 Session Management Interface
» Specifying a User-Defined Storage Module
» Problem Solution Discussion Using MySQL for Session BackingStore with Tomcat
» The Servlet and JSP Session Interface A Sample JSP Session Application
Show more