Java将date格式转为string格式
public class DataUtil {
public static String DateToString(Date date) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = format.format(date);
return str;
}
public static void main(String[] args) {
System.out.println(DataUtil.DateToString(new Date()));
}
}
Java将String格式转为date格式
public static Date string2Date2(String dateStr) throws ParseException {
String str = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(str);
Date date = sdf.parse(dateStr);
return date;
}
java string 转timestamp 写这个方法是由于在使用oracle数据库时,由于oracle数据库不支持string类型的时间格式,所以手动将保存到数据库的string类型时间转为timestamp格式,不过在后期发现,oracle数据库有只带将string转date的函数,不过还是将这个方法保存下来
public static Timestamp str2TimeStamp(String date){
Timestamp ts = new Timestamp(System.currentTimeMillis());
try {
ts = Timestamp.valueOf(date);
} catch (Exception e) {
e.printStackTrace();
}
return ts;
}
一个通用的string转 date的方法
/**
*
* @param dateStr
* @param formatStr 需要转换的时间格式
* @return
* @throws ParseException
*/
public static Date string2Date(String dateStr, String formatStr) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
Date date = sdf.parse(dateStr);
return date;
}
一个通用的date转string方法
/**
*
* @param date
* @param formatStr 需要转换的时间格式
* @return
*/
public static String date2Str(Date date, String formatStr) {
if (date == null) {
return null;
}
if (formatStr == null) {
formatStr = "yyyy-MM-dd HH:mm";
}
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
String dateStr = sdf.format(date);
return dateStr;
}
如果formatStr 为空的话,会默认设置时间格式为yyyy-MM-dd HH:mm.
获取当天00:00:00的时间
/**
* 获取当天00:00:00的时间
* @return
*/
public static Date getStartTime() {
Calendar todayStart = Calendar.getInstance();
todayStart.set(Calendar.HOUR_OF_DAY, 0);
todayStart.set(Calendar.MINUTE, 0);
todayStart.set(Calendar.SECOND, 0);
todayStart.set(Calendar.MILLISECOND, 0);
return todayStart.getTime();
}
获取当天23:59:59 的时间
/**
* 获取当天23:59:59 的时间
* @return
*/
public static Date getEndTime() {
Calendar todayEnd = Calendar.getInstance();
todayEnd.set(Calendar.HOUR_OF_DAY, 23);
todayEnd.set(Calendar.MINUTE, 59);
todayEnd.set(Calendar.SECOND, 59);
todayEnd.set(Calendar.MILLISECOND, 999);
return todayEnd.getTime();
}
比较两个时间
/**
* 比较date是否早于date2
*
* @param date1
* @param date2
* @return
* @throws Exception
*/
public static boolean compareDate(Date date1, Date date2) throws Exception {
if (date1 == null || date2 == null) {
throw new Exception("the two date cannot be null");
}
return date1.before(date2);
}