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

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

Introduction

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

Prototype

public static Date parseDate(final String str, final 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:SampleLang.java

public static void checkDate() throws InterruptedException, ParseException {
    //date1 created
    Date date1 = new Date();
    //Print the date and time at this instant
    System.out.println("The time right now is >>" + date1);
    //Thread sleep for 1000 ms
    Thread.currentThread().sleep(DateUtils.MILLIS_PER_MINUTE);
    //date2 created.
    Date date2 = new Date();
    //Check if date1 and date2 have the same day
    System.out.println("Is Same Day >> " + DateUtils.isSameDay(date1, date2));
    //Check if date1 and date2 have the same instance
    System.out.println("Is Same Instant >> " + DateUtils.isSameInstant(date1, date2));
    //Round the hour
    System.out.println("Date after rounding >>" + DateUtils.round(date1, Calendar.HOUR));
    //Truncate the hour
    System.out.println("Date after truncation >>" + DateUtils.truncate(date1, Calendar.HOUR));
    //Three dates in three different formats
    String[] dates = { "2005.03.24 11:03:26", "2005-03-24 11:03", "2005/03/24" };
    //Iterate over dates and parse strings to java.util.Date objects
    for (int i = 0; i < dates.length; i++) {
        Date parsedDate = DateUtils.parseDate(dates[i],
                new String[] { "yyyy/MM/dd", "yyyy.MM.dd HH:mm:ss", "yyyy-MM-dd HH:mm" });
        System.out.println("Parsed Date is >>" + parsedDate);
    }//from   w  w  w.  j a v a2 s.com
    //Display date in HH:mm:ss format
    System.out.println("Now >>" + DateFormatUtils.ISO_TIME_NO_T_FORMAT.format(System.currentTimeMillis()));
}

From source file:com.oa.product.action.MyDateUtils.java

/**
 *  ? { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
 * "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" }
 *///from   ww  w  . j a  v  a  2 s  .com
public static Date parseDate(Object str) {
    if (str == null) {
        return null;
    }
    try {
        return DateUtils.parseDate(str.toString(), parsePatterns);
    } catch (ParseException e) {
        return null;
    }
}

From source file:models.PullRequestEventTest.java

private PullRequestCommit createPullRequestCommit(String str) throws ParseException {
    PullRequestCommit commit = new PullRequestCommit();
    commit.created = DateUtils.parseDate(str, "yyyy-MM-dd");
    commit.save();//from w  w  w .j  av a2 s  . co m
    return commit;
}

From source file:models.TimelineItemTest.java

private TimelineItem createTimelineItem(String str) throws ParseException {
    final Date date = DateUtils.parseDate(str, "yyyy-MM-dd");
    return new TimelineItem() {
        @Override//from   w  w w .j ava2  s  .  c  om
        public Date getDate() {
            return date;
        }
    };
}

From source file:com.wedian.site.common.web.DateEditor.java

/**
 * //from w w  w .  j ava  2  s  .  c  o  m
 * 
 * @param text
 *            
 */
@Override
public void setAsText(String text) {
    if (text == null) {
        setValue(null);
    } else {
        String value = text.trim();
        if (emptyAsNull && "".equals(value)) {
            setValue(null);
        } else {
            try {
                setValue(DateUtils.parseDate(value, CommonAttributes.DATE_PATTERNS));
            } catch (ParseException e) {
                setValue(null);
            }
        }
    }
}

From source file:com.dominion.salud.pedicom.negocio.repositories.impl.PedidosRepositoryImpl.java

public List<Pedidos> findTransN() {
    String initDate = "01/01/2016";
    Date date = null;/*  w w w .  java 2s .  com*/
    List<LinParInt> list = linParIntRepository.getModulos();
    for (LinParInt lin : list) {
        if (lin.getLinParIntPK().getTipo().equals("MIN_FECHA_ENVIO")) {
            initDate = StringUtils.trim(lin.getParametro());
        }
    }
    try {
        date = DateUtils.parseDate(initDate, "dd/MM/yyyy");
    } catch (ParseException ex) {
    }
    return entityManager.createQuery(
            "from Pedidos where (transferido = 'N' or transferido = null or transferido ='T') and (estado = 'S') and fechaPedido > :fecha order by centros.linea, proveedor.codigo",
            Pedidos.class).setParameter("fecha", date).getResultList();
}

From source file:com.funtl.framework.smoke.core.modules.act.utils.DateConverter.java

/**
 * Convert String to Date//from   w  w  w .  j  av  a2 s. c o m
 *
 * @param value
 * @return
 * @throws ParseException
 */
private Date doConvertToDate(Object value) throws ParseException {
    Date result = null;

    if (value instanceof String) {
        result = DateUtils.parseDate((String) value,
                new String[] { DATE_PATTERN, DATETIME_PATTERN, DATETIME_PATTERN_NO_SECOND, MONTH_PATTERN });

        // all patterns failed, try a milliseconds constructor
        if (result == null && StringUtils.isNotEmpty((String) value)) {

            try {
                result = new Date(new Long((String) value).longValue());
            } catch (Exception e) {
                logger.error("Converting from milliseconds to Date fails!");
                e.printStackTrace();
            }

        }

    } else if (value instanceof Object[]) {
        // let's try to convert the first element only
        Object[] array = (Object[]) value;

        if (array.length >= 1) {
            value = array[0];
            result = doConvertToDate(value);
        }

    } else if (Date.class.isAssignableFrom(value.getClass())) {
        result = (Date) value;
    }
    return result;
}

From source file:com.omertron.slackbot.model.sheets.GameLogRow.java

/**
 * Take the row from the sheet API and convert it to this object
 *
 * @param valueRange// w w w  . ja  va  2  s  .co  m
 */
public final void processValueRange(ValueRange valueRange) {
    if (valueRange.getValues() == null || valueRange.getValues().isEmpty()) {
        return;
    }

    List<Object> row = valueRange.getValues().get(0);

    if (!row.isEmpty()) {
        try {
            this.date = DateUtils.parseDate(row.get(0).toString().substring(5), "dd MMM yy");
        } catch (ParseException ex) {
            LOG.info("Failed to parse date: '{}'", ex.getMessage());
        }
    }
    if (row.size() >= 2) {
        this.gameName = row.get(1).toString();
    }
    if (row.size() >= 3) {
        this.gameId = NumberUtils.toInt(row.get(2).toString(), 0);
    }
    if (row.size() >= 5) {
        this.chooser = row.get(4).toString();
    }
    if (row.size() >= 6) {
        this.attendees = row.get(5).toString();
    }
    if (row.size() >= 7) {
        this.winners = row.get(6).toString();
    }
    if (row.size() >= 9) {
        this.owner = row.get(8).toString();
    }

    LOG.info("{}", ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE));
}

From source file:com.yunmel.syncretic.core.BaseController.java

@InitBinder
public void initBinder(WebDataBinder binder) {
    // String??StringHTML?XSS
    binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
        @Override/*  www  .  j a  v  a 2  s  . c  o  m*/
        public void setAsText(String text) {
            setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
        }

        @Override
        public String getAsText() {
            Object value = getValue();
            return value != null ? value.toString() : "";
        }
    });
    // Date ?
    binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) {
            try {
                setValue(DateUtils.parseDate(text, "yyyy-MM-dd HH:mm:ss"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

    });
    // Timestamp ?
    binder.registerCustomEditor(Timestamp.class, new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) {
            Date date = null;
            try {
                date = DateUtils.parseDate(text, "yyyy-MM-dd HH:mm:ss");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            setValue(date == null ? null : new Timestamp(date.getTime()));
        }
    });

}

From source file:com.webbfontaine.valuewebb.irms.impl.assignment.snapshot.SnapshotManager.java

private static Date parseDate() {
    try {//from   w  ww  . ja  va2 s. c o m
        return DateUtils.parseDate("01-01-1970", "dd-MM-yyyy");
    } catch (ParseException e) {
        throw Throwables.propagate(e);
    }
}