package com.xuyigang1234.chp05.sec01;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class TestSimpleDateFormat { /** * 将日期对象格式化为指定格式的日期字符串 * @param date 传入的日期对象 * @param format 格式 * @return */ public static String formateDate(Date date,String geshi) { String result=""; SimpleDateFormat sdf= new SimpleDateFormat(geshi); if(date !=null) { result=sdf.format(date); } return result; } /** * 将日期字符串转换成一个日期对象 * @param dateStr 日期字符串 * @param format 格式 * @return * @throws ParseException */ public static Date formateD(String dateStr,String geshi) throws ParseException { SimpleDateFormat sdf= new SimpleDateFormat(geshi); return sdf.parse(dateStr); } public static void main(String[] args) throws ParseException { Date date= new Date(); SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd"); String date1 = sdf.format(date); System.out.println(date1); //formateDate String date2 = formateDate(date,"yyyy-MM-dd HH:mm:ss"); System.out.println(date2); //parse String dataStr="1989-11-02 18:01:41"; Date date3 = formateD(dataStr,"yyyy-MM-dd HH:mm:ss"); System.out.println(formateDate(date3,"yyyy-MM-dd HH:mm:ss")); }}
输出: 2018-11-222018-11-22 22:31:191989-11-02 18:01:41