Example usage for org.apache.commons.lang.time DateUtils parseDate

List of usage examples for org.apache.commons.lang.time DateUtils parseDate

Introduction

In this page you can find the example usage for org.apache.commons.lang.time DateUtils parseDate.

Prototype

public static Date parseDate(String str, String... parsePatterns) throws ParseException 

Source Link

Document

Parses a string representing a date by trying a variety of different parsers.

The parse will try each parse pattern in turn.

Usage

From source file:au.org.theark.core.dao.StudyDao.java

private String formatDate(String valueResult) {
    try {/*from  w ww .java  2s  . co  m*/
        DateFormat dateFormat = new SimpleDateFormat(au.org.theark.core.Constants.DD_MM_YYYY);
        String[] dateFormats = { au.org.theark.core.Constants.DD_MM_YYYY,
                au.org.theark.core.Constants.yyyy_MM_dd_hh_mm_ss_S, au.org.theark.core.Constants.yyyy_MM_dd };
        Date date = DateUtils.parseDate(valueResult, dateFormats);
        return (dateFormat.format(date));
    } catch (ParseException e) {
        return (valueResult);
    }
}

From source file:au.org.theark.core.dao.StudyDao.java

private String parseFilterValue(FieldType fieldType, String value) throws ParseException {
    String parsedValue = null;//  www  .  j  a  va 2s  . com
    if (fieldType.getName().equalsIgnoreCase("DATE")) {
        String[] dateFormats = { au.org.theark.core.Constants.DD_MM_YYYY,
                au.org.theark.core.Constants.yyyy_MM_dd_hh_mm_ss_S, "yyyy-MM-dd" };
        try {
            Date date = DateUtils.parseDate(value, dateFormats);
            SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
            parsedValue = (dt1.format(date));
        } catch (ParseException e) {
            log.error("exception parsing data " + value);
            throw e;
        }
    } else {
        parsedValue = value == null ? "" : value;
    }
    return parsedValue;
}

From source file:nu.mine.kino.projects.utils.ProjectUtils.java

public static Date createDateData(File target) throws IOException {
    Date parseDate = null;/* ww  w .  j  av a2 s .  c o  m*/
    String string = ReadUtils.readFile(target);
    String FORMAT = "yyyyMMdd";
    try {
        parseDate = DateUtils.parseDate(string, new String[] { FORMAT });
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        String tmp = string.replaceAll("\n", "");
        String dateStr = tmp.replaceAll("\r", "");
        try {
            parseDate = DateUtils.parseDate(dateStr, new String[] { FORMAT });
        } catch (ParseException e1) {
            e1.printStackTrace();
        }

    }
    return parseDate;
}

From source file:nu.mine.kino.projects.utils.ReadUtilsTest.java

@Test
public void testReadFile2() throws IOException {
    String base_date = ReadUtils.readFile(new File("base_date2.dat"));
    String series_date = ReadUtils.readFile(new File(SERIES_DAT_FILENAME));

    System.out.println("[" + base_date + "]");
    System.out.println("--------------");
    System.out.println("[" + series_date + "]");
    System.out.println("--------------");

    try {/*  ww w .j av  a 2s  .c  o  m*/
        Date parseDate = DateUtils.parseDate(base_date, new String[] { "yyyyMMdd" });
        Assert.fail("ParseException ?");
    } catch (ParseException e) {
    }

}

From source file:nu.mine.kino.projects.utils.ReadUtilsTest.java

@Test
public void testReadFile3() throws IOException, ParseException {
    Date date1 = ProjectUtils.createDateData(new File(DATE_DAT_FILENAME));
    System.out.println(date1);/*from   ww w. j a v  a2  s .  com*/
    Assert.assertEquals(DateUtils.parseDate("20151002", new String[] { "yyyyMMdd" }), date1);
    Date date2 = ProjectUtils.createDateData(new File("base_date2.dat"));
    System.out.println(date2);
    Assert.assertEquals(DateUtils.parseDate("20151002", new String[] { "yyyyMMdd" }), date2);

}

From source file:nu.mine.kino.projects.utils.Utils.java

/**
 * // * t??BMM/dd`???AdN?NZbg?B/* w w  w .j  a  v  a 2 s  .  c  o  m*/
 * 
 * @param dateStr
 * @return
 */
public static Date str2Date(String dateStr, String... parsePatterns) {
    if (isEmpty(dateStr)) {
        return null;
    }

    // // ?N
    // Calendar calendar = Calendar.getInstance();
    // calendar.setTime(new Date());
    // int year = calendar.get(Calendar.YEAR);
    //
    // try {
    // // String[] parsePatterns = new String[] { "MM/dd" };
    // Date dataDate = null;
    // DateUtils.parseDate(dateStr, parsePatterns);
    // if (parsePatterns == null || parsePatterns.length == 0) {
    // dataDate = DateUtils.parseDate(dateStr,
    // new String[] { "yyyy/MM/dd" });
    // }
    // dataDate = DateUtils.parseDate(dateStr, parsePatterns);
    // Calendar retCalendar = Calendar.getInstance();
    // retCalendar.setTime(dataDate);
    // retCalendar.set(Calendar.YEAR, year);
    // // System.out.println(retCalendar.getTime());
    // return retCalendar.getTime();
    // } catch (ParseException e) {
    // e.printStackTrace();
    // return null;
    // }
    String[] tmpParsePatterns = parsePatterns;
    if (parsePatterns.length == 0) {
        tmpParsePatterns = new String[] { "yyyyMMdd", "yyyy/MM/dd" };
    }

    try {
        return DateUtils.parseDate(dateStr, tmpParsePatterns);
    } catch (ParseException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.ala.harvester.BiocacheHarvester.java

/**
 * Main method for testing this particular Harvester
 *
 * @param args/*w  w  w .  ja v a2  s . co m*/
 */
public static void main(String[] args) throws Exception {
    String[] locations = { "classpath*:spring.xml" };
    ApplicationContext context = new ClassPathXmlApplicationContext(locations);
    BiocacheHarvester h = (BiocacheHarvester) context.getBean(BiocacheHarvester.class);
    Repository r = (Repository) context.getBean("repository");
    h.setRepository(r);

    if (args.length == 1) {
        h.setEndDate(new Date());
        if ("-lastYear".equals(args[0])) {
            h.setStartDate(DateUtils.addYears(h.getEndDate(), -1));
        } else if ("-lastMonth".equals(args[0])) {
            h.setStartDate(DateUtils.addMonths(h.getEndDate(), -1));
        } else if ("-lastWeek".equals(args[0])) {
            h.setStartDate(DateUtils.addWeeks(h.getEndDate(), -1));
        } else if ("-lastDay".equals(args[0])) {
            h.setStartDate(DateUtils.addDays(h.getEndDate(), -1));
        } else if ("-lastHour".equals(args[0])) {
            h.setStartDate(DateUtils.addHours(h.getEndDate(), -1));
        } else {
            //attempt to parse the date down to an acceptable date
            try {
                Date startDate = DateUtils.parseDate(args[0], new String[] { "yyyy-MM-dd" });
                h.setStartDate(startDate);
            } catch (java.text.ParseException e) {
                h.setStartDate(DateUtils.addDays(h.getEndDate(), -1));
            }
        }
    } else if (args.length == 2 && "-query".equals(args[0])) {
        h.setQuery(args[1]);
    }
    h.start(-1, true);

}

From source file:org.ala.harvester.FlickrHarvester.java

/**
 * @see org.ala.harvester.Harvester#start()
 *///  w  w  w.ja v  a 2s. co  m
@Override
public void start(int infosourceId) throws Exception {

    //get licences maps
    Map<String, Licence> licences = getLicencesMap();
    documentMapper.setLicencesMap(licences);

    int totalIndexed = 0;
    Date endDate = new Date();
    Date finalStartDate = DateUtils.parseDate("2004-01-01", new String[] { "yyyy-MM-dd" });
    if (System.getProperty("startDate") != null) {
        endDate = DateUtils.parseDate(System.getProperty("startDate"), new String[] { "yyyy-MM-dd" });
    }
    if (System.getProperty("endDate") != null) {
        finalStartDate = DateUtils.parseDate(System.getProperty("endDate"), new String[] { "yyyy-MM-dd" });
    }

    Date startDate = DateUtils.addDays(endDate, -1);
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

    // page through the images month-by-month
    while (startDate.after(finalStartDate)) {
        logger.info("Harvesting time period: " + df.format(startDate) + " to " + df.format(endDate));
        totalIndexed += indexTimePeriod(infosourceId, endDate, startDate);
        endDate = startDate;
        startDate = DateUtils.addDays(endDate, -1);
    }
    logger.info("Total harvested: " + totalIndexed);
}

From source file:org.ala.util.CleanupRepository.java

/**
 * @param args//from   w w  w.j  av a 2  s .  c o  m
 */
public static void main(String[] args) throws Exception {

    String filePath = null;
    Date thresholdDate = null;
    try {
        filePath = args[0];
        thresholdDate = DateUtils.parseDate(args[1], new String[] { "yyyyMMdd" });
    } catch (Exception e) {
        System.out.println("Usage: <absolute-file-path> <delete-before date (yyyyMMdd)>");
        System.exit(0);
    }

    //iterate through directory

    File file = new File(filePath);
    File[] dirs = file.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY);

    int deleting = 0;
    int keeping = 0;

    for (File currentDir : dirs) {
        System.out.println("Reading directory: " + currentDir.getAbsolutePath());
        Iterator<File> fileIterator = FileUtils.iterateFiles(currentDir, null, true);
        while (fileIterator.hasNext()) {
            File currentFile = fileIterator.next();
            Date lastModified = new Date(currentFile.lastModified());
            if (lastModified.before(thresholdDate)) {
                SimpleDateFormat sf = new SimpleDateFormat("dd MMM yyyy");
                System.out.println("Candidate for deletion: " + currentFile.getAbsolutePath()
                        + " last modified: " + sf.format(lastModified));
                FileUtils.forceDelete(currentFile);
                deleting++;
            } else {
                keeping++;
            }
        }
    }

    System.out.println("Keeping :" + keeping + ", deleting :" + deleting);

    System.out.println("Use the following command to remove empty directories.");

    System.out.println("find . -depth -empty -type d -exec rmdir {} \\;");
}

From source file:org.andrewberman.sync.PDFDownloader.java

private Date getStampFromArticlePage(String articleContent) {
    Date d = null;//from ww w.  j  a  v  a2 s .c  o m

    Matcher m = stampPattern.matcher(articleContent);
    while (m.find()) {
        /*
         * Chunk contains the article URL, and everything up until the next <li> element.
         */
        String chunk = m.group(1);

        try {
            //            System.out.println("Chunk: " + chunk);
            d = DateUtils.parseDate(chunk, new String[] { "y-M-d H:m:s" });
            //            System.out.println("Date: " + d);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    return d;
}