转换
- 获取当前时间,并转化为String类型
方法一:使用 SimpleDateFormat类:
SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String datetime = tempDate.format(new java.util.Date());
//也可以用这个
// String datetime = tempDate.format(new Date(System.currentTimeMillis()));
方法二:使用 Calendar类:
Calendar c = Calendar.getInstance();//可以用set()对每个时间域单独修改
int year = c.get(Calendar.YEAR);
//一般month都需要+1才表示当前月份
int month = c.get(Calendar.MONTH);
int date = c.get(Calendar.DATE);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
int second = c.get(Calendar.SECOND);
String nowTime = year + "/" + month + "/" + date + " " +hour + ":" + minute + ":" + second;
- 毫秒与日期间的转换
//时间戳转日期
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = dateformat.format(System.currentTimeMillis());
//日期转时间戳
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
//加上毫秒设置可确保精度,解决转换前后毫秒数不一致问题
long time = dateformat.parse("2016-09-02 23:02:17").getTime();
- 时间戳转Date
Date oldDate = new Date(registTime) ;
- 时间戳,String,Date之间转换
SimpleDateFormat dateFomrmat = new SimpleDateFormate("yyyy-MM-dd HH:mm:ss:SSS");
long registTime = mapper.get("数据库中的时间戳"); //“15111111111”
String time = dateFormate.formate(registTime);//2017-04-08 33:33:33
Date oldDate = dateFormate.parse(time); //Thu Mar 01 15:43:28 CST 2018
Calecdar cal = Calendar.getInstance();
cal.setTime(oldDate);
long 转换后的时间戳 = cal.getTimeInMillis();或者cal.getTime().getTime();
计算时间差
- 计算时间差
- 利用时间戳计算
int days = (endtime-begintime)/(10006060*24);
利用Calender类计算 - Date间相差天数
public static int getDiffOfDate(Date oldDate,Date newDate){
Calendar smallCalendar = Calendar.getInstance();
smallCalendar.setTiem(oldDate);
long beginTime = smallCalendar.TimeInMillis();
Calendar bigCalendar = Calendar.getInstance();
bigCalendar.setTime(newDate);
long endTime = smallCalendar.TimeInMillis();
int betweenDays = (int)((endTime-beginTime)/(1000*60*60*24));
bigCalendar.add(Calendar.DAY_OF_MONTH,-betweenDays);
bigCalendar.add(Calendar.DAY_OF_MONTH,-1);
if(smallCalendar.get(Calendar.DAY_OF_MONTH)==bigCalendar.get(Calendar.DAY_OF_MONTH))) {
betweenDays +=1;
}
return betweenDays;
}
时间获取
1.获取本周的时间
public static List<Long> getCurrentWeekRange() throws ParseException(){
List<Long> weekList = new Arraylist<>(2);
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.Mondy);
cal.setTime
}
生成时间戳
- System.currentTimeMillis(),它属于java.lang.System;
- Calendar.getInstance().getTimeInMillis(),它属于java.util.Calendar;
- new Date().getTime(),它属于java.util.Date;
- formate.parse().getTime()
通过上述比较,以运行100000为例,运行速度上currentTimeMillis>getTime>getTimeInMillis.
所以说在生成当前时间戳上,我建议大家采用currentTimeMillis方法,因为该方法运行速度最快