1 //Write a program that calculates the number of days between two dates in Java. 2 3 ImportJava.util.regex.Matcher;4 ImportJava.util.regex.Pattern;5 6 Public classDemo4 {7 Public Static voidMain (string[] args) {8 Try {9SYSTEM.OUT.PRINTLN (Difference of days ("2016-11-30", "2016-5-31")));Ten}Catch(Exception e) { One e.printstacktrace (); A } - } - the Private StaticPattern p = pattern.compile ("(\\d{4})-(\\d{1,2})-(\\d{1,2})"); - - Public Static intDays of difference (string A, string b)throwsException { -Matcher m =P.matcher (a); + if(!m.matches ()) - Throw NewException (); + intY1 = Integer.parseint (M.group (1)); A intM1 = Integer.parseint (M.group (2)); at intD1 = Integer.parseint (M.group (3)); -m =P.matcher (b); - if(!m.matches ()) - Throw NewException (); - inty2 = Integer.parseint (M.group (1)); - intM2 = Integer.parseint (M.group (2)); in intD2 = Integer.parseint (M.group (3)); - returnDays of difference (Y1, M1, D1, y2, M2, D2); to } + - Public Static intDifference in days (intY1,intM1,intD1,intY2,intM2,intD2) { the returnThe first few days (Y1, M1, D1)-The first few days (Y2, M2, D2); * } $ Panax Notoginseng Public Static intThe first day of the total (intYintMintd) { - intA = (y-1) * 365 + (Y-1)/4-(Y-1)/+ (Y-1)/400; the returnA +The first days of the year (Y, M, d); + } A the Public Static intThe first days of the year (intYintMintd) { + returnLeap year (y)? days before date [m] + D: Common year months ago [m] +D; - } $ $ Public Static BooleanLeap yearintyears) { - returnYear% 400 = = 0 | | (year% 4 = = 0 && Year% 100! = 0); - } the - Private Static Final int[] days of the month = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };Wuyi the Private Static Final int[] Number of days before the day of the month =New int[14], the number of days before the day of Run =New int[14]; - Static { Wu intn = 0; - for(inti = 1; I <= 12; i++) { AboutCommon year month ago days [i] =N; $days before date [i] = i > 2? n + 1: N; -n + =Days of the month [i]; - } -Common year months ago [13] =N; Adays before date [] = n + 1; + } the}
Java calculates the design of the number of days between two dates.