get Date from year index - Android java.util

Android examples for java.util:Year

Description

get Date from year index

Demo Code


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

public class Main {
    public static int MIN_YEAR = 1970;
    public static String DATE_FORMAT = "yyyy-MM-dd";

    public static Date getDate(int index) {
        int year = MIN_YEAR + index / 12;
        int month = index % 12;
        Calendar date = new GregorianCalendar(year, month, 1);
        Date d = date.getTime();//ww w.  ja  va  2 s . c o  m
        return d;
    }

    public static Date getDate(String dateStr) {
        if (dateStr == null || dateStr.equals("")) {
            return null;
        }
        SimpleDateFormat sf = new SimpleDateFormat(DATE_FORMAT);
        Date date = null;
        try {
            date = sf.parse(dateStr);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return date;
    }

    public static Date getDate(int mouths, int day) {
        int year = MIN_YEAR + mouths / 12;
        int month = mouths % 12;
        Calendar date = new GregorianCalendar(year, month, day);
        Date d = date.getTime();
        return d;
    }
}

Related Tutorials