Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import android.text.TextUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import java.util.Locale;

public class Main {
    static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
    private static Calendar calendarStartDate = Calendar.getInstance();
    private static Calendar calendarEndDate = Calendar.getInstance();

    public static int compareDates(String startDateString, String endDateString) {
        int interval = 0;

        if (TextUtils.isEmpty(startDateString) || TextUtils.isEmpty(endDateString)) {
            return -1;
        }
        try {
            java.util.Date startDate = dateFormat.parse(startDateString);
            java.util.Date endDate = dateFormat.parse(endDateString);

            if (startDate.after(endDate)) {
                return -1;
            }

            interval = compareDates(startDate, endDate);

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return interval;
    }

    public static int compareDates(java.util.Date startDate, java.util.Date endDate) {
        int interval = 0;

        calendarStartDate = Calendar.getInstance();
        calendarStartDate.set(Calendar.YEAR, startDate.getYear());
        calendarStartDate.set(Calendar.MONTH, startDate.getMonth());
        calendarStartDate.set(Calendar.DAY_OF_MONTH, startDate.getDate());

        calendarEndDate.set(Calendar.YEAR, endDate.getYear());
        calendarEndDate.set(Calendar.MONTH, endDate.getMonth());
        calendarEndDate.set(Calendar.DAY_OF_MONTH, endDate.getDate());

        long diff = calendarEndDate.getTimeInMillis() - calendarStartDate.getTimeInMillis();
        interval = (int) (diff / (24 * 60 * 60 * 1000) + 1); // plus one day

        return interval;
    }
}