1.时间戳转换为date
/**
* long 转换为data
* @Param time 格式一定为yyyy-MM-dd
*/
public static String longToDate(Long time) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dt = new Date(time);
String stime = sdf.format(dt);
return stime;
}
1.1时间戳转换为date
public static String getTime(long time){ //年 月 日 时 分 秒
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(System.currentTimeMillis()); //获取当前时间戳
}
2.date转换为时间戳
/**
* date 转换为long
* @Param time 格式一定为yyyy-MM-dd
*/
public static Long dateToLong(String time) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date choice = sdf.parse(time);
Long time = choice.getTime();
return time;
}
3.日期与日期比较
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//切记两个时间比较格式一定要相同
Date choice = dateFormat.parse("2019-09-06");//选择时间
Date current =
dateFormat.parse("2019-09-08");//当前时间
long min = choice.getTime()-current.getTime();
if(min>0){
选择时间晚于当前时间
}else{
选择时间早于当前时间
}
} catch (Exception e) {
e.printStackTrace();
}
4.获取前一个月的日期
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)-30);
Date date1 = calendar.getTime();
startl=date1.getTime();
starttime.setText(simpleDateFormat.format(date1));
kaishishijian = simpleDateFormat.format(date1);
5.获取当前时间
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
Date date = new Date(System.currentTimeMillis());
endtime.setText(simpleDateFormat.format(date));
endl=date.getTime();
6.获取上一个月第一天和上一个月最后一天
//设置初始时间
public void initTime() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
//获取前一个月第一天
Calendar calendar1 = Calendar.getInstance();
calendar1.add(Calendar.MONTH, -1);
calendar1.set(Calendar.DAY_OF_MONTH,1);
String firstDay = simpleDateFormat.format(calendar1.getTime());
startl = calendar1.getTime().getTime();
// starttime.setText(currentyear + "-" + month + "-" + "01");
starttime.setText(firstDay);
//获取前一个月最后一天
Calendar calendar2 = Calendar.getInstance();
calendar2.set(Calendar.DAY_OF_MONTH, 0);
String lastDay = simpleDateFormat.format(calendar2.getTime());
endl = calendar2.getTime().getTime();
endtime.setText(lastDay);
/* Calendar ca1 = Calendar.getInstance();
ca1.set(Calendar.DAY_OF_MONTH, ca1.getActualMinimum(Calendar.DAY_OF_MONTH));
String start = simpleDateFormat.format(ca1.getTime());
startl = ca1.getTime().getTime();
// starttime.setText(currentyear + "-" + month + "-" + "01");
starttime.setText(start);
//获取当前时间
Calendar ca = Calendar.getInstance();
ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
String last = simpleDateFormat.format(ca.getTime());
endl = ca.getTime().getTime();
endtime.setText(last);
*/
}
网友评论