Here you can find the source of daysBetween(String from, String to)
Parameter | Description |
---|---|
from | start date |
to | end date |
Parameter | Description |
---|---|
ParseException | erro info |
public static int daysBetween(String from, String to) throws ParseException
//package com.java2s; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class Main { /**//from w w w. ja v a2 s . c o m * return days between two date strings with user defined format. * @param from start date * @param to end date * @return daysBetween value * @throws ParseException erro info */ public static int daysBetween(String from, String to) throws ParseException { return daysBetween(from, to, "yyyyMMdd"); } /** * return days between two date strings with user defined format. * @param from start date * @param to end date * @param format date format * @return daysBetween value * @throws ParseException erro info */ public static int daysBetween(String from, String to, String format) throws ParseException { Date d1 = check(from, format); Date d2 = check(to, format); long duration = d2.getTime() - d1.getTime(); return (int) (duration / (1000 * 60 * 60 * 24)); // seconds in 1 day } /** * * @param s date string you want to check. * @param format string representation of the date format. For example, "yyyy-MM-dd". * @return date Date * @throws ParseException error info */ public static Date check(String s, String format) throws ParseException { if (s == null) throw new ParseException("date string to check is null", 0); if (format == null) throw new ParseException("format string to check date is null", 0); SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.KOREA); Date date = null; try { date = formatter.parse(s); } catch (ParseException e) { throw new ParseException(" wrong date:\"" + s + "\" with format \"" + format + "\"", 0); } if (!formatter.format(date).equals(s)) throw new ParseException("Out of bound date:\"" + s + "\" with format \"" + format + "\"", 0); return date; } }