参考资料:深入理解Java:SimpleDateFormat安全的时间格式化
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtil {
/**
* 获取当前日期:默认格式为yyyyMMdd
*
* @return String
*/
public static String getCurrentDate()
{
return getCurrentDateTime("yyyyMMdd");
}
/**
* 获取当前时间:默认格式为HHmmss
*
* @return String
*/
public static String getCurrentTime()
{
return getCurrentDateTime("HHmmss");
}
/**
* 获取当前日期时间:默认格式为yyyyMMddHHmmss
*
* @return String
*/
public static String getCurrentDateTime()
{
return getCurrentDateTime("yyyyMMddHHmmss");
}
/**
* 获取当前日期时间
*
* @param format
* @return String
*/
public static String getCurrentDateTime(String format)
{
return getDateStr(format);
}
/**
* 获取当前日期时间
*
* @param format
* @return String
*/
public static String getDateStr(String format) {
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.format(date);
}
public static String chgDateFormat(String srcDate, String srcFrmat, String tagFrmat) throws ParseException {
DateFormat srcFormat = new SimpleDateFormat(srcFrmat);
Date sDate = srcFormat.parse(srcDate);
DateFormat tagFormat = new SimpleDateFormat(tagFrmat);
return tagFormat.format(sDate);
}
/**
* 日期转换成字符串
*
* @param dateToFormat
* Date
* @param format
* String
* @return String
*/
public static String getDateStr(Date dateToFormat, String format)
{
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.format(dateToFormat);
}
public static void main(String[] args) {
try {
System.out.println(chgDateFormat("00:00:00","HH:mm:ss", "HHmmss"));
} catch (ParseException e) {
e.printStackTrace();
}
String now = getDateStr(new Date(), "yyyyMMddHHmmss");
System.out.println(now);
}
}