您的位置:首页 > 其它

(原创)分享自己写的几个工具类(五)时间计算工具类

2017-06-16 16:07 381 查看
话不多说,直接上代码,拿来就能通用

/**
* Created by 熊叶平 on 2017/6/16 0016.
* 时间操作工具类
*/
public class TimeUtil {

/**
* 将时间转换为时间戳
*
* @param s  时间字符串
* @param s2 时间格式字符串 必须和时间字符串s对应 如 yyyy-MM-dd HH:mm:ss
* @return
*/
public static String datetoStamp(String s, String s2) {
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(s2);
Date date = null;
try {
date = simpleDateFormat.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
long ts = date.getTime() / 1000;
res = String.valueOf(ts);
return res;
}

/**
* 将时间戳转换为时间
*
* @param s  时间戳字符串
* @param s2 时间格式字符串 必须和时间字符串s对应 如 yyyy-MM-dd HH:mm:ss
* @return
*/
public static String stamptoDate(String s, String s2) {
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(s2);
long lt = new Long(s);
Date date = new Date(lt);
res = simpleDateFormat.format(date);
return res;
}

/**
* 得到给定时间的当天结束时间(秒级别时间戳)
*
* @param date
* @return
*/
public static String getEndTime(Date date) {
Calendar todayEnd = Calendar.getInstance();
todayEnd.setTime(date);
// HOUR_OF_DAY 24小时制
todayEnd.set(Calendar.HOUR_OF_DAY, 23); // Calendar.HOUR 12小时制
todayEnd.set(Calendar.MINUTE, 59);
todayEnd.set(Calendar.SECOND, 59);
todayEnd.set(Calendar.MILLISECOND, 999);
long endtime = todayEnd.getTimeInMillis() / 1000;
return "" + endtime;
}

/**
* 获取当前日期是星期几
*
* @param date
* @return
*/
public static String getWeekOfDate(Date date) {
String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0)
w = 0;
return weekDays[w];
}

/**
* 将短时间格式字符串转换为时间 yyyy-MM-dd
*
* @param strDate
* @return
*/
public static Date strToDate(String strDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(strDate, pos);
return strtodate;
}

/**
* 判断是否润年
*
* @param ddate
* @return
*/
public static boolean isLeapYear(String ddate) {

/**
* 详细设计: 1.被400整除是闰年,否则:
* 2.不能被4整除则不是闰年
* 3.能被4整除同时不能被100整除则是闰年
*/
Date d = strToDate(ddate);
GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
gc.setTime(d);
int year = gc.get(Calendar.YEAR);
if ((year % 400) == 0)
return true;
else if ((year % 4) == 0) {
if ((year % 100) == 0)
return false;
else
return true;
} else
return false;
}

/**
* 获取一个月的最后一天
*
* @param dat
* @return
*/
public static String getEndDateOfMonth(String dat) {// yyyy-MM-dd
String str = dat.substring(0, 8);
String month = dat.substring(5, 7);
int mon = Integer.parseInt(month);
if (mon == 1 || mon == 3 || mon == 5 || mon == 7 || mon == 8 || mon == 10 || mon == 12) {
str += "31";
} else if (mon == 4 || mon == 6 || mon == 9 || mon == 11) {
str += "30";
} else {
if (isLeapYear(dat)) {
str += "29";
} else {
str += "28";
}
}
return str;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: