Get last month day of week - Android java.util

Android examples for java.util:Month

Description

Get last month day of week

Demo Code

/*/*from   ww  w. j a va2 s  .  co  m*/
 * Copyright (C) 2016 venshine.cn@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main {
    /**
     * Get last month day of week
     *
     * @return
     */
    public static int getLastMonthDayOfWeek() {
        return getMonthDayOfWeek(getCurrentYear(), getCurrentMonth() - 1);
    }

    /**
     * Get month day of week by year, month
     *
     * @param year
     * @param month
     * @return
     */
    public static int getMonthDayOfWeek(int year, int month) {
        Calendar cal = Calendar.getInstance();
        String dateString = year + "-"
                + (month > 9 ? month : ("0" + month)) + "-01";
        String pattern = "yyyy-MM-dd";
        Date date = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            date = sdf.parse(dateString);
        } catch (ParseException e) {
        }
        if (date != null) {
            cal.setTime(date);
            int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
            if (week_index < 0) {
                week_index = 0;
            }
            return week_index;
        }
        return -1;
    }

    /**
     * Get current year
     *
     * @return
     */
    public static int getCurrentYear() {
        return Calendar.getInstance().get(Calendar.YEAR);
    }

    /**
     * Get current month
     *
     * @return
     */
    public static int getCurrentMonth() {
        return Calendar.getInstance().get(Calendar.MONTH) + 1;
    }
}

Related Tutorials