java开发常用_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;   }  }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值