DateUtils.java [src/java/m/multiobj] Revision:   Date:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package m.multiobj;

import java.text.ParseException;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;

/**
 *
 * @author Andre Dozier <andre.dozier@rams.colostate.edu>
 */
public class DateUtils {

    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
    private static final DateTime BASE_DATE;

    static {
        BASE_DATE = new DateTime(1900, 1, 1, 0, 0);
    }

    public static DateTime toDate(String dateString, String formatString) throws ParseException {
        if (dateString == null || dateString.isEmpty()) {
            return null;
        }
        return DateTime.parse(dateString, DateTimeFormat.forPattern(formatString));
    }

    public static DateTime toDate(double yearsAndMonthFractions, boolean isOffset) {
        if (isOffset) {
            yearsAndMonthFractions -= 0.08; // 1998.08 is January 1998. 1999.00 is December 1998.
        }
        int year = (int) yearsAndMonthFractions;
        int month = (int) Math.round(12 * (yearsAndMonthFractions - year)) + 1;
        return new DateTime(year, month, 1, 0, 0);
    }

    public static DateTime toDate(int year, int doy) {
        return new DateTime(year, 1, 1, 0, 0).plusDays(doy - 1);
    }

    public static DateTime toDate(long milliseconds) {
        return new DateTime(milliseconds);
    }

    public static long toTimeSinceEpoch(DateTime date) {
        return date.getMillis();
    }

    public static long toTimeSince1900(DateTime date) {
        return date.getMillis() - BASE_DATE.getMillis();
    }

    public static int getYear(DateTime date) {
        return date.getYear(); 
    }

    public static int getDOY(DateTime date) {
        return date.getDayOfYear(); 
    }
}