Java開發常用方法彙總

時間的處理:

 public static String getDate() {
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  return sdf.format(new Date());
 }

 public static long getDateTime(String pattern) {
  SimpleDateFormat sdf = new SimpleDateFormat(pattern);
  return getDate(pattern, sdf.format(System.currentTimeMillis())).getTime();
 }

 public static String getDate(String pattern) {
  SimpleDateFormat sdf = new SimpleDateFormat(pattern);
  return sdf.format(new Date());
 }

 public static String getDate(String pattern, long times) {
  SimpleDateFormat sdf = new SimpleDateFormat(pattern);
  Date date = new Date();
  date.setTime(times);
  return sdf.format(date);
 }

 public static String getDate(String pattern, Date date) {
  SimpleDateFormat sdf = new SimpleDateFormat(pattern);
  return sdf.format(date);
 }

 public static Date getDate(String pattern, String source) {
  SimpleDateFormat sdf = new SimpleDateFormat(pattern);
  try {
   return sdf.parse(source);
  } catch (ParseException e) {
  }
  return new Date();
 }

如果對時間格式解析不正確可能是時區的問題,可以設置時區來解決。

private Date getDate(String pattern, String source){
  SimpleDateFormat sdf = new SimpleDateFormat(pattern,new Locale("China"));
  try {
   return sdf.parse(source);
  } catch (ParseException e) {
  }
  return new Date();
 }

更多信息可以查詢java.text.SimpleDateFormat類中對時間格式的定義

字符串的處理:

 public static float str2float(String s, int defaultValue) {
  try {
   return Float.parseFloat(s);
  } catch (Exception e) {
  }
  return defaultValue;
 }

 public static double str2double(String s, double defaultValue) {
  try {
   return Double.parseDouble(s);
  } catch (Exception e) {
  }
  return defaultValue;
 }

 public static String obj2String(Object s, String defaultValue) {
  try {
   if (s != null)
    return ((String) s).trim();
  } catch (Exception e) {
  }
  return defaultValue;
 }

 public static int str2int(String s, int defaultValue) {
  try {
   if (s != null)
    return Integer.parseInt(s.trim());
   else
    return defaultValue;
  } catch (Exception e) {
   return defaultValue;
  }
 }

 public static long str2long(String s, long defaultValue) {
  try {
   if (s != null)
    return Long.parseLong(s.trim());
   else
    return defaultValue;
  } catch (Exception e) {
   return defaultValue;
  }
 }

 

發佈了49 篇原創文章 · 獲贊 15 · 訪問量 25萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章