Here you can find the source of getValidDate(String unknownDate)
public static String getValidDate(String unknownDate)
//package com.java2s; //License from project: Apache License import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; public class Main { public static final String DEFAULT_FOMATE = "yyyyMMdd"; public static String getValidDate(String unknownDate) { if (unknownDate == null || !unknownDate.matches("[\\+|-]?[0-9]+")) { return null; }/*from w w w . j a v a 2s . c o m*/ Calendar calendar = Calendar.getInstance(); int len = unknownDate.length(); if (len < 4) { // 0, +2, -3, -16 int days = Integer.parseInt(unknownDate); calendar.add(Calendar.DAY_OF_MONTH, days); return getDateStr(calendar); } else if (unknownDate.charAt(0) != '+' && unknownDate.charAt(0) != '-') { if (len == 8) { // 20160622 return unknownDate; } else if (len == 6) { // 160622 return (calendar.get(Calendar.YEAR) / 100) + unknownDate; } else if (len == 4) { // 0622 return calendar.get(Calendar.YEAR) + unknownDate; } } return null; } public static String getDateStr(Calendar calendar, String format) { if (calendar == null || format == null) { return null; } try { SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.US); return dateFormat.format(calendar.getTime()); } catch (Exception e) { } return null; } public static String getDateStr(Calendar calendar) { return getDateStr(calendar, DEFAULT_FOMATE); } public static String getDateStr(Date date, String format) { if (date == null) { return null; } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return getDateStr(calendar, format); } public static String getDateStr(Date date) { return getDateStr(date, DEFAULT_FOMATE); } public static String getDateStr(long time_millis, String format) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(time_millis); return getDateStr(calendar, format); } public static String getDateStr(long time_millis) { return getDateStr(time_millis, DEFAULT_FOMATE); } public static String getDateStr(String format) { return getDateStr(System.currentTimeMillis(), format); } public static String getDateStr() { return getDateStr(DEFAULT_FOMATE); } }