您的位置:首页 > 编程语言 > Java开发

【JAVA核心技术】工具类----时间工具类

2013-06-08 16:59 309 查看
/**
* 两个时间相差的天数.
*/
public static int getIntervalDays(Date fDate, Date oDate) {

if (null == fDate || null == oDate) {
return -1;
}
long intervalMilli = oDate.getTime() - fDate.getTime();
return (int) (intervalMilli / (24 * 60 * 60 * 1000));

}
public class TimeUtils {

public static String converTime(long timestamp) {
long currentSeconds = System.currentTimeMillis() / 1000;
long timeGap = currentSeconds - timestamp;// 与现在时间相差秒数
String timeStr = null;
if (timeGap > 24 * 60 * 60) {// 1天以上
timeStr = timeGap / (24 * 60 * 60) + "天前";
} else if (timeGap > 60 * 60) {// 1小时-24小时
timeStr = timeGap / (60 * 60) + "小时前";
} else if (timeGap > 60) {// 1分钟-59分钟
timeStr = timeGap / 60 + "分钟前";
} else {// 1秒钟-59秒钟
timeStr = "刚刚";
}
return timeStr;

}
public static String getStandardTime(long timestamp) {
SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日 HH:mm");
Date date = new Date(timestamp * 1000);
sdf.format(date);
return sdf.format(date);
}
}


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

/**
* 获取日期的星期数
* 格式化字符串存在区分大小写
* EEEE代表星期,MMMM代表中文月份
* @return
*/
public static String getWeekofDate2(){
Date date = new Date();
SimpleDateFormat dateFm = new SimpleDateFormat("EEEE");
String str = dateFm.format(date);
return str;
}

/**
* 得到几天前的时间
* @param d
* @param day
* @return
*/
public static Date getDateBefore(Date d,int day){
Calendar now =Calendar.getInstance();
now.setTime(d);
now.set(Calendar.DATE,now.get(Calendar.DATE)-day);
return now.getTime();
}

/**
* 得到几天后的时间
* @param d
* @param day
* @return
*/
public static Date getDateAfter(Date d,int day){
Calendar now =Calendar.getInstance();
now.setTime(d);
now.set(Calendar.DATE,now.get(Calendar.DATE)+day);
return now.getTime();
}

Java获取当前日期的前一个月,前一天的时间  如下:

 

Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -1);    //得到前一天
calendar.add(Calendar.MONTH, -1);    //得到前一个月
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH)+1;
注意月份加一

/**
* 判断当前日期是星期几<br>
* <br>
* @param pTime 修要判断的时间<br>
* @return dayForWeek 判断结果<br>
* @Exception 发生异常<br>
*/
public static int dayForWeek(String pTime) throws Exception {
format = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(format.parse(pTime));
int dayForWeek = 0;
if(c.get(Calendar.DAY_OF_WEEK) == 1){
dayForWeek = 7;
}else{
dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
}
return dayForWeek;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: