package cn.zwq.convert; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * 日期类型与字符串类型的相互转换 * * @author zwq * @version V1.0 * @Date 2016年10月11日 下午8:28:04 * */ public class DateConvert { public static void main(String[] args) { Date date = stringToDate("1979-01-01"); //Date date = stringToDate("19790101"); //Date date = stringToDate("1979.01.01"); //Date date = stringToDate("1979/01/01"); //Date date = stringToDate("1979年01月01日"); String string = dateToString(date); System.out.println(string); } public static Date stringToDate(String string) { SimpleDateFormat[] simpleDateFormats = { new SimpleDateFormat("yyyy-MM-dd"), new SimpleDateFormat("yyyyMMdd"), new SimpleDateFormat("yyyy.MM.dd"), new SimpleDateFormat("yyyy/MM/dd"), new SimpleDateFormat("yyyy年MM月dd日") }; for (int i = 0; i < simpleDateFormats.length; i++) { try { Date date = simpleDateFormats[i].parse(string); return date; } catch (ParseException e) { continue; } } return null; } public static String dateToString(Date date) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日"); String string = simpleDateFormat.format(date); return string; } }
时间: 2024-10-01 04:49:38