package jmeter;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.util.Date;
public class time_function {
// format格式为 :yyyy-MM-dd HH:mm:ss
// 得到当前时间的时间戳
public static long getNowStamp() throws java.text.ParseException {
Date date = new Date();
long currentTime = date.getTime();
return currentTime;
}
// 得到String类型的当前时间
public static String getNowString(String format) {
Date date = new Date();
SimpleDateFormat sf = new SimpleDateFormat(format);
String nowDate = sf.format(date);
return nowDate;
}
// 格式化时间,
public static String getformatString(String format, String time) throws java.text.ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
Date date = dateFormat.parse(time);
String d = dateFormat.format(date);
return d;
}
// 时间计算
public static String dateCalculation(String date, String format, int number) throws java.text.ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
Date dat = dateFormat.parse(date);
Calendar cal = Calendar.getInstance();
cal.setTime(dat);
//1是对年份操作,2是对月份操作,3是对星期操作,5是对日期操作,11是对小时操作,12是对分钟操作,13是对秒操作,14是对毫秒操作
cal.add(5, number);
SimpleDateFormat sf = new SimpleDateFormat(format);
String d = sf.format(cal.getTime());
return d;
}
// 计算两个日期之间的距离
public static int getTimeDistance(Date beginDate, Date endDate) {
Calendar beginCalendar = Calendar.getInstance();
beginCalendar.setTime(beginDate);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);
long beginTime = beginCalendar.getTime().getTime();
long endTime = endCalendar.getTime().getTime();
int betweenDays = (int) ((endTime - beginTime) / (1000 * 60 * 60 * 24));// 计算两个时间毫秒数之差大于一天的天数
// 使endCalendar减去这些天数,将问题转换为两时间的毫秒数之差不足一天的情况
endCalendar.add(Calendar.DAY_OF_MONTH, -betweenDays);
// 再使endCalendar减去1天
endCalendar.add(Calendar.DAY_OF_MONTH, -1);
// 比较两日期的DAY_OF_MONTH是否相等
if (beginCalendar.get(Calendar.DAY_OF_MONTH) == endCalendar.get(Calendar.DAY_OF_MONTH)) {
//相等说明确实跨天了
return betweenDays + 1;
} else {
//相等说明没有跨天了
return betweenDays + 0;
}
}
// String转为时间戳
public static long stringToStamp(String time, String dateformat) throws java.text.ParseException {
SimpleDateFormat format = new SimpleDateFormat(dateformat);
Date date = format.parse(time);
return date.getTime();
}
// 时间戳转为string
public static String stampToString(Long stamp, String dateformat) throws java.text.ParseException {
SimpleDateFormat format = new SimpleDateFormat(dateformat);
String d = format.format(stamp);
return d;
}
// 时间戳转为date格式
public static Date stampToDate(Long stamp, String dateformat) throws java.text.ParseException {
SimpleDateFormat format = new SimpleDateFormat(dateformat);
String d = stampToString(stamp, dateformat);
Date date = format.parse(d);
return date;
}
// String转为Date
public static Date stringToDate(String time, String dateformat) throws java.text.ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = dateFormat.parse(time);
return date;
}
}