Example usage for java.text DateFormat parse

List of usage examples for java.text DateFormat parse

Introduction

In this page you can find the example usage for java.text DateFormat parse.

Prototype

public Date parse(String source) throws ParseException 

Source Link

Document

Parses text from the beginning of the given string to produce a date.

Usage

From source file:net.longfalcon.newsj.util.DateUtil.java

public static DateTime parseNNTPDate(String dateString) {
    DateTime dateTime = null;//from  ww w. j a v  a  2s.c o m

    try {
        dateTime = RFC_dateFormatter.parseDateTime(dateString);
    } catch (IllegalArgumentException e) {
        // do nothing
    }

    int i = 0;
    while (dateTime == null && i < _dateFormats.length) {
        try {
            DateTimeFormatter fmt = DateTimeFormat.forPattern(_dateFormats[i]);
            dateTime = fmt.parseDateTime(dateString);
        } catch (IllegalArgumentException e) {
            // do nothing
        }
        i++;
    }

    i = 0;
    while (dateTime == null && i < _dateFormats.length) {
        try {
            DateFormat javaFormatter = new SimpleDateFormat(_dateFormats[i]);
            Date date = javaFormatter.parse(dateString);
            dateTime = new DateTime(date);
        } catch (Exception e) {
            // do nothing
        }
        i++;
    }
    if (dateTime == null) {
        _log.error(String.format("Unable to parse date string \'%s\'", dateString));
        dateTime = new DateTime();
    }
    return dateTime;
}

From source file:Util.java

public static Timestamp formatTimestamp(Timestamp datetime) {
    try {/*  w ww .ja  v  a2  s  .c om*/
        DateFormat formatter;
        String dateFormat = datetime.toString();
        System.out.println("Truoc:" + datetime);
        formatter = new SimpleDateFormat("dd/MM/yyyy");
        Date date = (Date) formatter.parse(dateFormat);
        java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
        System.out.println("Sau:" + timeStampDate);
        return timeStampDate;
    } catch (ParseException e) {
        System.out.println("Exception :" + e);
        return null;
    }
}

From source file:com.l2jfree.gameserver.script.DateRange.java

/**
 * Create a DateRange with a single String and a Date formatter
 * The initial String is split on "-"/*ww  w  . j a  v a 2  s.  c om*/
 * @param dateRange
 * @param format
 * @return DateRange
 */
public static DateRange parse(String dateRange, DateFormat format) {
    String[] date = dateRange.split("-");
    if (date.length == 2) {
        try {
            Date start = format.parse(date[0]);
            Date end = format.parse(date[1]);

            return new DateRange(start, end);
        } catch (ParseException e) {
            _log.warn("Invalid Date Format for a dateRange.", e);
        }
    }
    return new DateRange(null, null);
}

From source file:Main.java

public static void previousDateString(String dateString) throws ParseException {
    DateFormat inputDateFormat = new SimpleDateFormat("dd-MM-yyyy");
    DateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    Calendar now = Calendar.getInstance();
    Calendar calendar = Calendar.getInstance();
    Date myDate = inputDateFormat.parse(dateString);
    calendar.setTime(myDate);/*from ww w.java  2s.c  om*/
    calendar.set(Calendar.HOUR_OF_DAY, now.get(Calendar.HOUR_OF_DAY));
    calendar.set(Calendar.MINUTE, now.get(Calendar.MINUTE));

    String output = outputDateFormat.format(calendar.getTime());
    System.out.println(output);
}

From source file:io.hops.examples.spark.kafka.StreamingLogs.java

private static JSONObject parser(String line, String appId) {
    JSONObject jsonLog = new JSONObject(line);
    JSONObject index = new JSONObject();
    String priority, logger, thread, timestamp;
    priority = logger = thread = timestamp = null;

    //Sample line:
    String[] attrs = jsonLog.getString("message")
            .substring(0, StringUtils.ordinalIndexOf(jsonLog.getString("message"), " ", 4)).split(" ");
    String message = jsonLog.getString("message")
            .substring(StringUtils.ordinalIndexOf(jsonLog.getString("message"), " ", 4) + 1);
    try {//from  w w  w  .j  a  v  a 2  s .c  o  m
        priority = attrs[2];
        logger = attrs[3];
        //thread = attrs[5];
        timestamp = attrs[0] + " " + attrs[1];
        //Convert timestamp to appropriate format
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss,SSS");
        Date result = df.parse(timestamp);
        Locale currentLocale = Locale.getDefault();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", currentLocale);
        timestamp = format.format(result);

    } catch (Exception ex) {
        LOG.log(Level.WARNING, "Error while parsing log, setting default index parameters:{0}",
                ex.getMessage());
        message = jsonLog.getString("message");
        priority = "parse error";
        logger = "parse error";
        //thread = "parse error";
        timestamp = "parse error";
    }

    index.put("message", message);
    index.put("priority", priority);
    index.put("logger_name", logger);
    index.put("timestamp", timestamp);
    index.put("application", appId);
    index.put("host", jsonLog.getJSONObject("beat").getString("hostname"));
    index.put("project", Hops.getProjectName());
    index.put("jobname", Hops.getJobName());
    if (jsonLog.getString("source").contains("/")) {
        index.put("file",
                jsonLog.getString("source").substring(jsonLog.getString("source").lastIndexOf("/") + 1));
    } else {
        index.put("file", jsonLog.getString("source"));
    }

    return index;
}

From source file:com.aliyun.odps.ship.common.Util.java

public static String getSessionDir(String sid) throws IllegalArgumentException {
    String subdir;//from  w w w. j av  a2  s .c  o m
    if (sid == null) {
        subdir = null;
    } else if (sid.length() > 8) {
        try {
            DateFormat format = new SimpleDateFormat("yyyyMMdd");
            format.parse(sid.substring(0, 8));
            subdir = sid.substring(0, 8);
        } catch (ParseException e) {
            subdir = sid;
        }
    } else {
        subdir = sid;
    }
    return getSessionBaseDir() + "/sessions/" + subdir + "/" + sid;
}

From source file:com.collabnet.ccf.core.utils.DateUtil.java

/**
 * Converts the given Date object into another date object with the
 * specified time zone information./*from w  w  w.  j  a  v a2 s .  c o  m*/
 * 
 * @param date
 *            - The date that is to be converted to a different time zone.
 * @param toTimeZone
 *            - the time zone to which the date object should be converted.
 * @return the new Date object in the specified time zone.
 * @throws ParseException
 */
public static Date convertDate(Date date, String toTimeZone) throws ParseException {
    Calendar cal = new GregorianCalendar(TimeZone.getTimeZone(toTimeZone));
    cal.setTime(date);
    DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss.SSS Z");
    df.setCalendar(cal);
    return df.parse(df.format(cal.getTime()));
}

From source file:com.mycompany.asyncreq.Main.java

public static void ObjToCsv(Root tRoot, String reg) throws IOException {
    List<Tdataset> arForms = tRoot.dataset;
    List<ArrayList<String>> tradeDatas = new ArrayList<ArrayList<String>>();

    int count = 0;
    for (Iterator<Tdataset> j = arForms.iterator(); j.hasNext();) {

        Tdataset tmp = j.next();//from   www . j  a v a  2s. c o  m
        DateFormat format = new SimpleDateFormat("yyyyMM");
        try {
            Date date = format.parse(tmp.getperiod());
            Ttradedata trade = new Ttradedata(tmp.getrtCode(), tmp.getptCode(), tmp.getrgCode(),
                    tmp.getqtCode(), tmp.getestCode(), date, tmp.getTradeQuantity(), tmp.getNetWeight(),
                    tmp.getTradeValue(), tmp.getcmdCode());

            tradeDatas.add(trade.setString());
            if (tradeDatas.size() % 10000 == 0) {
                writeToCSV(tradeDatas,
                        "data/" + tRoot.dataset.get(0).getptCode() + "_" + count + "_" + reg + ".csv");
                count++;
                tradeDatas.clear();
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }

    writeToCSV(tradeDatas, "data/" + tRoot.dataset.get(0).getptCode() + "_" + reg + ".csv");
    tradeDatas.clear();
    System.out.println("ok!");

}

From source file:edu.coeia.charts.LineChartPanel.java

private static String getMonthName(String date) throws ParseException {
    DateFormat fullDate = new SimpleDateFormat("dd/MM/yyyy");
    DateFormat month = new SimpleDateFormat("MMMM");
    Date d = fullDate.parse(date);

    String m = month.format(d);/*from   ww  w  . ja  va 2 s .co m*/
    return (m);
}

From source file:com.esofthead.mycollab.core.utils.DateTimeUtils.java

/**
 * Trim hour-minute-second of date instance value to zero.
 * //from   w w  w.ja  va 2s .c  o  m
 * @param value
 * @return
 */
public static Date trimHMSOfDate(Date value) {
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    try {
        return df.parse(df.format(value.getTime()));
    } catch (ParseException e) {
        throw new MyCollabException(e);
    }
}