日期字符串转换注意事项及实例(经典)

之前有经常遇到这个问题,临时先写下做个备注,已测试

/**
	 * 把日期字符串转换成日期	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");
	}


你可能感兴趣的:(《UI》)