Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * Copyright (C) 2010 Nullbyte <http://nullbyte.eu>
 *
 * 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.
 */

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

public class Main {
    /**
     * Determines what year a transaction belongs to.
     * 
     * If the given <code>day</code> of the given <code>month</code> for the current year
     * is in the future the transaction is probably from last year.
     * 
     * @param month     The month, where January is 1.
     * @param day       The day of the month, starting from 1.
     * @return          An ISO 8601 formatted date.
     */
    public static String getTransactionDate(String month, String day) {
        return getTransactionDate(Integer.parseInt(month), Integer.parseInt(day));
    }

    /**
     * Determines what year a transaction belongs to.
     * 
     * If the given <code>day</code> of the given <code>month</code> for the current year
     * is in the future the transaction is probably from last year.
     * 
     * @param month     The month, where January is 1.
     * @param day       The day of the month, starting from 1.
     * @return          An ISO 8601 formatted date.
     */
    public static String getTransactionDate(int month, int day) {
        month--; // Java-months start at 0
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        int currentYear = cal.get(Calendar.YEAR);
        cal.set(currentYear, month, day, 0, 0);
        if (cal.getTime().after(Calendar.getInstance().getTime())) {
            //If the transaction is in the future the year is probably of by +1.
            cal.add(Calendar.YEAR, -1);
        }
        return sdf.format(cal.getTime());
    }
}