計算紀念日
前言:某一天小白問大白我們結婚多久了,大白思索良久,拿出日曆看了看,說到估計xxx天了吧,這時只見天空頓時灰暗(大白暗叫不好),一個巴掌最終還是拍響了。。。。。
分享一個自己耍朋友的時候用的紀念日計算工具案例吧。
測試:
java代碼
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class Live {
//控制檯輸入流
private Scanner cin = new Scanner(System.in);
public static void main(String[] args) throws ParseException {
Live l = new Live();
String time = l.infoStringDate();
while (!l.isDate(time)) {time = l.reInfoStringDate();}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(time);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int miss = l.infoMiss();
while (miss != -1) {
show(calendar, miss, date);
calendar.setTime(date);
miss = l.infoMiss();
}
System.out.println("歡迎下次使用");
}
/**
* 顯示計算結果
* @param calendar
* @param miss
* @param date
*/
public static void show(Calendar calendar, int miss, Date date) {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd EE");
calendar.add(Calendar.DATE, miss);
date = calendar.getTime();
System.out.println("請注意你們的" + miss + "天的紀念日是:" + sdf1.format(date));
}
public int infoMiss() {
System.out.println("輸入特殊紀念時間(如:520,輸入-1結束)");
return cin.nextInt();
}
/**
* 檢查輸入的時間是否滿足格式要求
* @param date 時間字符串
* @return 是否滿足要求
*/
public boolean isDate(String date) {
// 第一格式檢查
boolean ok = date.matches("[1-9]{1}[0-9]{3}-(0[1-9]{1}|1[1-2]{1}|10)-[0-3]{1}[0-9]{1}");
// 第二日期校驗
String[] data = date.split("[-/.+]");
ok = ok && isMonthAndDay(date);
return ok;
}
private boolean isMonthAndDay( String date ) {
String[] data = date.split("[-/.+]");
String month=data[1], day = data[2];
boolean ok = true;
//二月
if (month.matches("0[2]||2")) {
if(isRunYear(Integer.parseInt(data[0]))) {// 閏年
if (!day.matches("0[1-9]||[1-9]||1[0-9]||2[0-9]")) {
ok = false;
}
}else {// 非閏年
if (!day.matches("0[1-9]||[1-9]||1[0-9]||2[0-8]")) {
ok = false;
}
}
} else {// 2月份以外的大小月 【1大2小3大xxxx】
if (month.matches("0[13578]||[13578]||1[02]")) {//大月
if (!day.matches("0[1-9]||[1-9]||[12][0-9]||3[01]")) {
ok = false;// 天數不對
}
} else if (month.matches("0[469]||[469]||11")) {//小月
if (!day.matches("0[1-9]||[1-9]||[12][0-9]||30")) {
ok = false; // 天數不對
}
}
}
return ok;
}
public boolean isRunYear(int year) {
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {// 是閏年
return true;
} else {return false;}
}
/**
* 輸入初始時間,已字符串的格式輸入
* @return 返回輸入的字符串格式
*/
public String infoStringDate() {
System.out.println("請輸入愛情開始的時間:格式(2016-01-07)");
return cin.nextLine();
}
public String reInfoStringDate() {
System.out.println("輸入時間不符合要求,請按要求重新輸入(格式:2016-01-07)");
return cin.nextLine();
}
}
代碼未經專業測試,望指教。
暢想:集成一個短信,或者郵件提醒的服務,對用戶指定特殊紀念日發送短信提醒(做大做強-)。