1. 程式人生 > >Java的幾個有用小Util函數(日期處理和http)

Java的幾個有用小Util函數(日期處理和http)

content lex .get get sta mmd 第幾天 service ret

/**
* 依據日期返回當前日期是一年的第幾天
* @param date
* @return
*/
public static int orderDate(String dateStr) {

if(dateStr == null || dateStr.trim().length() == 0) return 0;

int dateSum = 0;
int year = Integer.valueOf(dateStr.substring(0, 4));
int month = Integer.valueOf(dateStr.substring(5, 7));
int day = Integer.valueOf(dateStr.substring(8, 10));
for (int i = 1; i < month; i++) {
switch (i) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
dateSum += 31;
break;
case 4:
case 6:
case 9:
case 11:
dateSum += 30;
break;
case 2:
if (((year % 4 == 0) & (year % 100 != 0)) | (year % 400 == 0))
dateSum += 29;
else
dateSum += 28;
}
}
return dateSum = dateSum + day;

}


/**
* @ 獲得兩個日期之間的 格式化的日期(天)集合
*/
public static List<String> getMMDDList(String start, String end) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdfout = new SimpleDateFormat("MMdd");
List<String> list = new ArrayList<String>();

try {
Date date_start = sdf.parse(start);
Date date_end = sdf.parse(end);
Date date = date_start;
Calendar cd = Calendar.getInstance();


while (date.getTime() <= date_end.getTime()) {
list.add(sdfout.format(date));
cd.setTime(date);
cd.add(Calendar.DATE, 1);// 添加一天
date = cd.getTime();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}


/**
*
* @方法名:testWsdlConnection
* @功能說明:測試webservice地址是否可用
* @return
*/
public static boolean testWsdlConnection(String address){
boolean flag = false;
try {
URL urlObj = new URL(address);
HttpURLConnection oc = (HttpURLConnection) urlObj.openConnection();
oc.setUseCaches(false);
oc.setConnectTimeout(5000); //設置超時時間5s
int status = oc.getResponseCode();//請求狀態
if(200 == status){
return true;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
return flag;
}

Java的幾個有用小Util函數(日期處理和http)