Posted In: Date, Java Core

Convert date string to one format to another

This function will convert date string format to another format.

public static String formatTo(String date, String patternFrom, String patternTo) {
	if (StringUtils.isBlank(date)) {
		return date;
	}

	try {
		DateFormat dfFrom = new SimpleDateFormat(patternFrom);
		DateFormat dfTo = new SimpleDateFormat(patternTo);
		return dfTo.format(dfFrom.parse(date));
	} catch (Exception e) {
		LOGGER.warn("Date [" + date + "] could not be formatted from [" 
				+ patternFrom + "] to [" + patternTo
				+ "], returning orignal string: " + e.getMessage());
		return date;
	}
}

Test

@Test
public void formatTo() throws ParseException {
	System.out.println(DateUtil.formatTo("02/2015", "MM/yyyy", "yyyyMM"));
}

Tags:

by , on April 2nd, 2017

  • Categories