package com.xmlmind.misc;

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

/**
 * Support code needed to implement <tt>sample_plugins/rss/rss.xslt</tt>.
 */
public final class DateUtil {
    private DateUtil() {}

    // -----------------------------------------------------------------------

    /**
     * Parses a date like <tt>2019-02-22T14:00:00Z</tt> and 
     * formats it to <tt>Fri, 22 Feb 2019 15:00:00 +0100</tt>.
     * <p>This format is required by the 
     * <a href="http://www.rssboard.org/rss-specification">RSS spec</a>.
     */
    public static String format(String value) {
        try {
            value = value.trim();
            if (value.length() > 0) {
                // Date formats are not synchronized. It is recommended to
                // create separate format instances for each thread.

                SimpleDateFormat inFormat = 
                    new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
                inFormat.setLenient(false);

                Date date = inFormat.parse(value);

                SimpleDateFormat outFormat = 
                    new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", 
                                         Locale.US);

                return outFormat.format(date);
            }
        } catch (Exception e) {
            System.err.println("Cannot format date \"" + value + "\": " + 
                               e.getMessage());
        }

        return value;
    }
}
