JAVA常用的时间格式化方法

来源:百度文库 编辑:神马文学网 时间:2024/04/29 07:13:22
/**
* 根据想得到的时间格式返回string
* @parma formatStyle 要格式化的格式 e.g:yyyy-MM-dd HH:mm:ss
* @param date
* @return
*/
public static String getFormatDate(String formatStyle) {
return new SimpleDateFormat(formatStyle).format(new Date().getTime());
}
/**
* 根据想得到的时间格式返回string
* @parma formatStyle 要格式化的格式 e.g:yyyy-MM-dd HH:mm:ss
* @param time
* @return
*/
public static String getFormatDate(String formatStyle,Date time) {
return new SimpleDateFormat(formatStyle).format(time);
}
/**
* 把形式为yyyy-MM-dd HH:mm:ss的字符串转化为Date
* @param strDate
* @return
*/
public static Date convertStrToDate(String strDate) {
Date date = null;
try {
date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(strDate);
} catch (ParseException e) {
System.out.println("convert string to date error!");
e.printStackTrace();
}
return date;
}
/**
* 得到日期字符串形式为20080908
* @return
*/
public static  String getChinaDateString() {
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH)+1;
int date = calendar.get(Calendar.DATE);
String strYear = String.valueOf(year);
String strMonth = month<10? "0"+ month : String.valueOf(month);
String strDate = date<10? "0"+date : String.valueOf(date);
return strYear+strMonth+strDate;
}