核心:日期转换器 SImpleDateFormat
日期对象转换成字符串 strDate = new SimleDateFormat("格式参数").format(date);
字符串转换成日期对象 data = new SimpleDateFormat("格式参数").parse(strDate);
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateTool { /** * 将日期类型转换为指定格式的字符串 * 注意:格式串的格式和日期字符串的格式要保持一致,否无法进行转换 * * @param strDate 被转化的日期字符串 * @param strFormat 日期字符串的格式 * @return 转换之后的日期对象 */ public static Date convertString2Date(String strDate, String strFormat) { // 返回值(根据业务需求确定默认的返回值) // Date date = new Date(); Date date = null; // 如果格式串为空,则使用默认格式串 if (strFormat == null) { strFormat = "yyyy-MM-dd HH:mm:ss"; } // 创建日期格式化处理类的实例对象 SimpleDateFormat sdf = new SimpleDateFormat(strFormat); try { // 进行转换处理 date = sdf.parse(strDate); } catch (ParseException e) { // 异常处理 System.out.println("日期字符串转化为日期对象异常:" + e.getMessage()); } return date; } /** * 将日期类型转换为指定格式的字符串 * * @param date 被转化的日期类型 * @param strFormat 日期字符串的格式 * @return 转换之后的日期格式串 */ public static String convertDate2String(Date date, String strFormat) { // 返回值 String strDate = null; // 如果格式串为空,则使用默认格式串 if (strFormat == null) { strFormat = "yyyy-MM-dd HH:mm:ss"; } // 创建日期格式化处理类的实例对象 SimpleDateFormat sdf = new SimpleDateFormat(strFormat); // 进行格式化处理 strDate = sdf.format(date); return strDate; } }
