String类型转Date类型
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = simpleDateFormat.parse(time);
或者一行
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2020-04-20 00:00:00.000")
- 问题一:Unhandled exception:java.text.ParseException
- 解决方式:在方法声明后加
throws ParseException
,例如下:
@Override
public List<PolicyEntity> findByTime(String time) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = simpleDateFormat.parse(time);
return policyMapper.findByTime(date);
}
Date类型转String类型
/**
* 获取现在时间
*
* @return返回字符串格式 yyyy-MM-dd HH:mm:ss
*/
public static String getStringDate() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
return dateString;
}
计算两个日期间隔天数
firstDate和lastDate为date类型
int days = (int) ((lastDate.getTime().getTime() - firstDate.getTime().getTime()) / (1000 * 3600 * 24));
System.out.println("总共间隔时间天数"+days);
两个日期字符串之间的日期集合
/**
* 获取两个日期字符串之间的日期集合
* @param startDate
* @param endDate
* @return
*/
public static List<String> getBetweenDate(Date startDate, Date endDate){
// 时间格式转换为 2020/Jan/20 格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MMM/dd", Locale.UK);
// 声明保存日期集合
List<String> list = new ArrayList<String>();
//用Calendar 进行日期比较判断
Calendar calendar = Calendar.getInstance();
while (startDate.getTime()<=endDate.getTime()){
// 把日期添加到集合
list.add(sdf.format(startDate));
// 设置日期
calendar.setTime(startDate);
//把日期增加一天
calendar.add(Calendar.DATE, 1);
// 获取增加后的日期
startDate=calendar.getTime();
}
return list;
}
日期月份转英文格式
主要调整SimpleDateFormat里的格式为自己所需样子,加上参数Locale.UK即可
// 2020-04-20 >> Apr 20 20120
public String changeYMDtoEn(String dateYMD) throws Exception{
Date dates = TypeChange.StrToDate(dateYMD);
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy", Locale.UK); // 月日年
return sdf.format(dates);
}
public String changeYMDtoEn(Date dateYMD) throws Exception{
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy", Locale.UK); // 月日年
return sdf.format(dateYMD);
}
例如上述我的例子中
// 时间格式转换为 2020/Jan/20 格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MMM/dd", Locale.UK);