(1)获取当前时间,返回时间格式为:yyyy-MM-dd HH:mm:ss
public static Date getNowDate() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
ParsePosition pos = new ParsePosition(8);
Date currentTime_2 = formatter.parse(dateString, pos);
return currentTime_2;
}
(2)字符串转换为指定的时间格式,返回格式为:yyyy-MM-dd或者是yyyy年MM月dd日 HH时mm分ss秒间的相互转换
public static Date getStringToDate() {
DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
DateFormat format 2= new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
Date date = null;
String str = null;
str = "2020-4-3";
try {
/*date = format1.parse(str);*/ //"yyyy-MM-dd"
data = format2.parse(str); //"yyyy年MM月dd日 HH时mm分ss秒"
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
(3)当前时间转换为指定格式的字符串,如格式:yyyy-MM-dd HH:mm:ss或者yyyy-MM-dd或者HH:mm:ss
public static String getDateToString() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
return dateString;
}
(4)得到现在的时间、现在时间的小时、分钟、秒
public static String getStringTime() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd HHmmss");
String dateString = formatter.format(currentTime);
//String hour = dateString.subString(11,13);
//String min = dateString.subString(14,16);
return dateString;
}
(5)判断一个日期(字符串类型)是否为闰年,闰年的判断方式:
①.被400整除是闰年,否则: ②.不能被4整除则不是闰年 ③.能被4整除同时不能被100整除则是闰年,能被4整除同时能被100整除则不是闰年
public static boolean isLeapYear(String date) {
Date d = strToDate(ddate);
GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
gc.setTime(d);
int year = gc.get(Calendar.YEAR);
if ((year % 400) == 0)
return true;
else if ((year % 4) == 0) {
if ((year % 100) == 0)
return false;
else
return true;
} else
return false;
}