日付文字列変換の注意事項とインスタンス(クラシック)

1377 ワード

前によくこの問題に出会って、臨時に先に書いて注釈をして、すでにテストしました
/**
	 *  	date   format ,
	 *   :getDateString("20180323143557882","yyyyMMddHHmmss") getDateString("2018-03-23143557882","yyyy-MM-ddHHmmss"); getDateString("20180323143557882","yyyyMMdd_HHmmss"); 
	 * @param date	   :20180323143557882
	 * @param format			   yyyyMMddHHmmss
	 * @return
	 * @author huyanbin
	 */
	public static Date getDateString(String date, String format) {
		try {
			if (format == null)
				format = "yyyy-MM-dd HH:mm:ss";
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			System.out.println(sdf.parse(date));
			return sdf.parse(date);
		} catch (Exception e) {
			return null;
		}

	}

	/**
	 *  
	 * @param date		Sat Mar 24 06:39:42 CST 2018
	 * @param format	yyyy-MM-dd HH:mm:ss
	 * @return
	 * @author huyanbin
	 */
	public static String dateFormatConversion(Date date, String format) {
		try {
			if (format == null)
				format = "yyyy-MM-dd HH:mm:ss";
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			System.out.println(sdf.format(date));  
			return sdf.format(date);
		} catch (Exception e) {
			return null;
		}

	}
public static void main(String[] args) {
		dateFormatConversion(getDateString("20180323143557882","yyyyMMddHHmmss"),"yyyyMMdd_HHmmss");
	}