RelativeDateFormat.java 1.77 KB
/*
 * Decompiled with CFR 0_118.
 */
package com.day.cq.analytics.sitecatalyst.util;

import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RelativeDateFormat
extends SimpleDateFormat {
    protected Date base = new Date();
    protected static final String RELATIVE_DATE_REGEX = "([+-]\\d+)([dDmMyY])";
    protected Pattern pattern = Pattern.compile("([+-]\\d+)([dDmMyY])");

    public RelativeDateFormat() {
    }

    public RelativeDateFormat(String pattern) {
        super(pattern);
    }

    public RelativeDateFormat(String pattern, DateFormatSymbols formatSymbols) {
        super(pattern, formatSymbols);
    }

    public RelativeDateFormat(String pattern, Locale locale) {
        super(pattern, locale);
    }

    public Date parseRelative(String text) throws ParseException {
        Matcher matcher = this.pattern.matcher(text);
        if (matcher.matches()) {
            int amount = Integer.parseInt(matcher.group(1).replace("+", ""));
            String unit = matcher.group(2).toLowerCase();
            GregorianCalendar cal = new GregorianCalendar();
            cal.setTime(this.base);
            int field = 0;
            if (unit.equals("d")) {
                field = 5;
            } else if (unit.equals("m")) {
                field = 2;
            } else if (unit.equals("y")) {
                field = 1;
            }
            cal.add(field, amount);
            return cal.getTime();
        }
        return this.parse(text);
    }

    public void setBaseDate(Date base) {
        if (base != null) {
            this.base = base;
        }
    }
}