Java tutorial
//package com.java2s; /* * The MIT License (MIT) * Copyright (C) 2016 DCODE TECHNOLOGIES LTD * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; public class Main { private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/yyyy", Locale.getDefault()); 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: Calendar now = getCurrentExpDate(); String year = String.valueOf(now.get(Calendar.YEAR)); int yearDigit = Integer.parseInt(text.substring(3, 4)); 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: Calendar now2 = getCurrentExpDate(); String currentYearStr2 = String.valueOf(now2.get(Calendar.YEAR)); String yearStr = text.substring(0, 3) + currentYearStr2.substring(0, 2) + text.substring(3, 5); Date expiry = simpleDateFormat.parse(yearStr); if (expiry.before(now2.getTime())) { // 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) { e.printStackTrace(); } // If an exception is thrown we clear out the text return ""; } private static Calendar getCurrentExpDate() { Calendar now = Calendar.getInstance(); now.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH), 0, 0, 0); return now; } }