Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class Main {

    public static long betweenMonth(String t1, String t2, String... patterns) {
        return betweenTime(Calendar.YEAR, t1, t2, patterns) * 12 + betweenTime(Calendar.MONTH, t1, t2, patterns);
    }

    private static long betweenTime(int what, String t1, String t2, String... patterns) {
        if (patterns.length == 0) {
            throw new RuntimeException("must give me a pattern");
        }
        Date d1 = getDate(t1, patterns[0]);
        Date d2 = getDate(t2, patterns.length > 1 ? patterns[1] : patterns[0]);
        if (d1 != null && d2 != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(d1);
            int i1 = calendar.get(what);
            calendar.setTime(d2);
            int i2 = calendar.get(what);
            return i1 - i2;
        }
        return Long.MIN_VALUE;
    }

    public static Date getDate(String t, String pattern) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern, Locale.getDefault());
        try {
            Date date = dateFormat.parse(t);
            Calendar calendar = Calendar.getInstance();
            calendar.clear();
            calendar.setTime(date);
            return date;
        } catch (ParseException e) {
            return null;
        }
    }
}