日付変換ヘルプクラス
3886 ワード
/**
*
*
*
*
*/
public class ConvertDateUtil {
/**
*
*
* @param time
* 1. 60
* 2. 13:05
* 3. 1 28 12:02
* 4. 1
* 5. 54
* 6. 3
* 7. 2014-7-12 00:05
* 8. 2013-4-12 10:05:40
* @return
*/
public static String FOMAT_MINIUTE_BEFORE = " ";
public static String FOMAT_TODAY_TIME = " ";
public static String FOMAT_DATE_TIME = " ";
public static String FOMAT_HOUR_BEFORE = " ";
public static String FOMAT_SECOND_BEFORE = " ";
public static String FOMAT_DAY_BEFORE = " ";
public static Date convert(String time) {
try {
time = time.trim();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
Date today = new Date();
Calendar c = Calendar.getInstance();
if (time.contains(FOMAT_MINIUTE_BEFORE)) {
int miniutes = Integer.parseInt(time.substring(0,time.indexOf(FOMAT_MINIUTE_BEFORE)).trim());
return new Date(c.getTime().getTime() - miniutes * 60 * 1000);
} else if (time.contains(FOMAT_TODAY_TIME)) {
String hour = time.substring(FOMAT_TODAY_TIME.length(),time.length()).trim();
return sdf2.parse(c.get(Calendar.YEAR) + "-"+ c.get(Calendar.MONTH) + "-" + c.get(Calendar.DATE)+ " " + hour);
} else if (time.contains(FOMAT_DATE_TIME)) {
time = time.replace(" ", "-").replace(" ", "");
return sdf2.parse(c.get(Calendar.YEAR) + "-" + time);
} else if(time.contains(FOMAT_HOUR_BEFORE)){
int hours = Integer.parseInt(time.substring(0,time.indexOf(FOMAT_HOUR_BEFORE)).trim());
return new Date(today.getTime() - hours * 60 * 60 * 1000);
}else if(time.contains(FOMAT_SECOND_BEFORE)){
int seconds = Integer.parseInt(time.substring(0,time.indexOf(FOMAT_SECOND_BEFORE)).trim());
return new Date(today.getTime() - seconds * 1000);
}else if(time.contains(FOMAT_DAY_BEFORE)){
int days = Integer.parseInt(time.substring(0,time.indexOf(FOMAT_DAY_BEFORE)).trim());
return new Date(today.getTime() - days * 24 * 60 * 60 * 1000);
}else if(time.split("-").length==3&&time.split(":").length==2){
return sdf2.parse(time);
}else if(time.split("-").length==3&&time.split(":").length==3){
return sdf.parse(time);
}else if(time.split("-").length==3&&time.indexOf(":")< 0){
return sdf3.parse(time);
}else{
return new Date();
}
} catch (Exception e) {
return new Date();
}
}
public static void main(String[] args) throws ParseException {
System.out.println(ConvertDateUtil.convert(" 60 "));
System.out.println(ConvertDateUtil.convert(" 13:05 "));
System.out.println(ConvertDateUtil.convert(" 1 28 12:02 "));
System.out.println(ConvertDateUtil.convert(" 1 "));
System.out.println(ConvertDateUtil.convert(" 54 "));
System.out.println(ConvertDateUtil.convert(" 3 "));
System.out.println(ConvertDateUtil.convert("2014-7-12 00:05"));
System.out.println(ConvertDateUtil.convert("2013-4-12 10:05:40"));;
System.out.println(ConvertDateUtil.convert("2013-4-12"));;
}
}