get Months For Date - Android java.util

Android examples for java.util:Month

Description

get Months For Date

Demo Code


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

import android.util.Log;

public class Main {

    public static int getMonthsForDate(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);//from   w  ww. j  a v  a  2 s.c  o m
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int mouths = (year - 1970) * 12 + month;
        return mouths;
    }

    public static int getMonthsForDate(String dateStr) {
        if (dateStr == null || dateStr.equals("")) {
            Log.i("CalendarUtil", "date is null");
            return -1;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date;
        int mouths = -1;
        try {
            date = format.parse(dateStr);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH);
            mouths = (year - 1970) * 12 + month;
            Log.i("CalendarUtil", date.toString());

        } catch (ParseException e) {
            e.printStackTrace();
        }
        Log.i("CalendarUtil", mouths + "");
        return mouths;
    }
}

Related Tutorials