package eu.dnetlib.miscutils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * various date utilities.
 * 
 * @author michele
 * 
 */
public class DateUtils {

	private static final SimpleDateFormat ISO8601FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US);

	public static String getDate_ISO8601(final Date date) {
		final String result;
		synchronized (ISO8601FORMAT) {
			result = ISO8601FORMAT.format(date);
		}
		return result.substring(0, result.length() - 2) + ":" + result.substring(result.length() - 2);
	}

	public static String getDate_ISO8601(final long date) {
		return getDate_ISO8601(new Date(date));
	}

	public static long now() {
		return new Date().getTime();
	}

	public static String now_ISO8601() {
		return getDate_ISO8601(new Date());
	}

	public static Date parse(final String dateArg) {
		String date = new String(dateArg);

		if ("".equals(date)) { return null; }

		try {
			if (date.endsWith("Z")) {
				date = date.replace("Z", "+0000");
			} else if (date.length() < 20) {
				date += "+0000"; // NOPMD
			} else {
				final String end = date.substring(date.length() - 3);
				date = date.substring(0, date.length() - 3) + end.replace(":", "");
			}

			synchronized (ISO8601FORMAT) {
				return ISO8601FORMAT.parse(date);
			}
		} catch (ParseException e) {
			throw new IllegalStateException("invalid iso8601 date '" + dateArg + "' (even after normalizing it to '" + date + "')");
		}
	}

	public static Date parse(final String date, final String format) {
		if ("".equals(date)) { return null; }
		try {
			final SimpleDateFormat sdf = new SimpleDateFormat(format);
			return sdf.parse(date);
		} catch (ParseException e) {
			throw new IllegalStateException("invalid date '" + date + "' (format: " + format + ")");
		}
	}

}
