Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Calendar;
import java.util.Date;

public class Main {
    public static String formatExpirationDate(String text) {

        try {
            switch (text.length()) {
            case 1:
                int digit = Integer.parseInt(text);

                if (digit < 2) {
                    return text;
                } else {
                    return "0" + text + "/";
                }
            case 2:
                int month = Integer.parseInt(text);
                if (month > 12 || month < 1) {
                    // Invalid digit
                    return text.substring(0, 1);
                } else {
                    return text + "/";
                }
            case 3:
                if (text.substring(2, 3).equalsIgnoreCase("/")) {
                    return text;
                } else {
                    text = text.substring(0, 2) + "/" + text.substring(2, 3);
                }
            case 4:
                int yearDigit = Integer.parseInt(text.substring(3, 4));
                String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
                int currentYearDigit = Integer.parseInt(year.substring(2, 3));
                if (yearDigit < currentYearDigit) {
                    // Less than current year invalid
                    return text.substring(0, 3);
                } else {
                    return text;
                }
            case 5:
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/yy");
                simpleDateFormat.setLenient(false);
                Date expiry = simpleDateFormat.parse(text);
                if (expiry.before(new Date())) {
                    // Invalid exp date
                    return text.substring(0, 4);
                } else {
                    return text;
                }
            default:
                if (text.length() > 5) {
                    return text.substring(0, 5);
                } else {
                    return text;
                }
            }

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // If an exception is thrown we clear out the text
        return "";
    }
}