Helper to compare i.e two months in different years

This method will help in comparing two dates by trimming date format to our specific format. So we avoid unnecessary data.

Sample:

We compare two months in different years. First date is:

2017-10-10 10:00

First we convert it to milliseconds using `SimpleDateFormat`.

We want know only time for

2017-10

So after we get millisecond, we can convert it to another one `yyyy-MM-dd` using code below:

public long getTimeInMillis(long milliSeconds, String dateFormat) {
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat, Locale.forLanguageTag("pl"));
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(milliSeconds);
    String format = formatter.format(calendar.getTime());

    long milli = milliSeconds;

    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat, Locale.forLanguageTag("pl"));
    try {
        Date parse = sdf.parse(format);
        Calendar c = Calendar.getInstance();
        c.setTime(parse);
        milli = c.getTimeInMillis();
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return milli;
}

Leave a Reply

Your email address will not be published. Required fields are marked *