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:com.sudoku.data.model.User.java

public static User buildFromAvroUser(com.sudoku.comm.generated.User user) {
    User resultUser = new User();
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH);
    resultUser.pseudo = user.getPseudo();
    resultUser.profilePicturePath = user.getProfilePicturePath();
    resultUser.ipAddress = user.getIpAddress();
    resultUser.salt = user.getSalt();/*from   ww  w  . j  a v  a2  s  .  com*/
    try {
        resultUser.birthDate = df.parse(user.getBirthDate());
        resultUser.createDate = df.parse(user.getCreateDate());
        resultUser.updateDate = df.parse(user.getUpdateDate());
    } catch (ParseException ex) {
        LOGGER.error(ex.toString());
    }
    resultUser.contactCategories = new LinkedList<>(); // NEED TO SERIALIZE THIS BUT NOT TRANSFER IT
    return resultUser;
}

From source file:com.box.boxjavalibv2.utils.ISO8601DateParser.java

public static Date parse(String input) throws java.text.ParseException {

    // NOTE: SimpleDateFormat uses GMT[-+]hh:mm for the TZ which breaks
    // things a bit. Before we go on we have to repair this.
    DateFormat df = mThreadLocalSimpleDateFormat.get();

    // this is zero time so we need to add that TZ indicator for
    if (input.endsWith("Z")) {
        input = input.substring(0, input.length() - 1) + "GMT-00:00";
    } else {//from  w w  w . j  av  a2s .  co m
        int inset = 6;

        String s0 = input.substring(0, input.length() - inset);
        String s1 = input.substring(input.length() - inset, input.length());

        input = s0 + "GMT" + s1;
    }

    return df.parse(input);

}

From source file:com.jd.survey.service.security.UserService.java

public static boolean isDateValid(String date, String dateFormat) {
    try {//from www. jav a2  s.c  o  m
        DateFormat df = new SimpleDateFormat(dateFormat);
        df.setLenient(false);
        df.parse(date);
        return true;
    } catch (ParseException e) {
        return false;
    }
}

From source file:com.taobao.tdhs.client.util.ConvertUtil.java

public static Long getTimeFromString(String stringVal, @Nullable Calendar cal) throws SQLException {
    if (stringVal == null) {
        return null;
    }//from www  .j  a v a  2  s  .c o  m
    String val = stringVal.trim();
    if (val.length() == 0) {
        return null;
    }
    if (val.equals("0") || val.equals("0000-00-00") || val.equals("0000-00-00 00:00:00")
            || val.equals("00000000000000") || val.equals("0")) {
        Calendar calendar = null;
        if (cal != null) {
            calendar = Calendar.getInstance(cal.getTimeZone());
        } else {
            calendar = Calendar.getInstance();
        }
        calendar.set(Calendar.YEAR, 1);
        calendar.set(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        return calendar.getTimeInMillis();
    }

    DateFormat dateFormat;
    if (val.length() == "yyyy-MM-dd".length()) {
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    } else {
        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }
    if (cal != null) {
        TimeZone timeZone = cal.getTimeZone();
        dateFormat.setTimeZone(timeZone);
    }
    try {
        return dateFormat.parse(val).getTime();
    } catch (ParseException e) {
        throw new SQLException("Parse date failure:" + val);
    }
}

From source file:br.com.nordestefomento.jrimum.utilix.DateUtil.java

/**
 * <p>//from w w  w  . j  a  v a2 s  . co m
 * Converte um objeto <code>String</code> em um objeto
 * <code>java.util.Date</code> atravs do objeto
 * <code>java.text.DateFormat</code> especificado.
 * </p>
 * 
 * @param dateAsString
 *            - um valor de data em forma de <code>String</code>.
 * @param dateFormat
 *            - formatador para objetos <code>java.util.Date</code>.
 * @return Objeto <code>java.util.Date</code> convertido a partir do objeto
 *         <code>String</code>
 * 
 * @throws IllegalArgumentException
 *             caso o objeto <code>String</code> no seja um valor vlido de
 *             data suportado pelo formatador.
 * @since 0.2
 */
public static Date parse(String dateAsString, DateFormat dateFormat) {

    Date date = null;

    if (dateAsString == null) {
        throw new NullPointerException("A String a ser convertida no pode ter valor [null].");
    }

    if (dateFormat == null) {
        throw new NullPointerException("O formatador no pode ter valor [null].");
    }

    try {

        date = dateFormat.parse(dateAsString);

    } catch (ParseException e) {

        String msg = "A String [" + dateAsString + "] deve ser uma data vlida no formato";
        if (dateFormat instanceof SimpleDateFormat) {
            SimpleDateFormat sdf = (SimpleDateFormat) dateFormat;
            msg += " [" + sdf.toPattern() + "].";

        } else {
            msg += " especificado.";
        }

        IllegalArgumentException iae = new IllegalArgumentException(msg);
        iae.initCause(e);
        throw iae;
    }

    return date;
}

From source file:cn.ipanel.apps.portalBackOffice.util.CommonsFiend.java

/**
 * //from   ww w  .j av  a2  s. c om
 * 
 * @param date
 *            yyyy-MM
 * @return
 * @author lixiang
 * @throws ParseException
 * @create 2008-9-22 01:59:33
 * @since
 */
public static List getDatesList(String date) throws ParseException {
    DateFormat format = new SimpleDateFormat("yyyy-MM");
    Calendar time = Calendar.getInstance();
    time.clear();
    Date d1 = format.parse(date);
    time.setTime(d1);
    int day = time.getActualMaximum(Calendar.DAY_OF_MONTH);
    DateFormat formats = new SimpleDateFormat(Defines.FORMAT_DATE_STRING);
    List list = new ArrayList();
    for (int i = 1; i <= day; i++) {
        String s = format.format(d1) + "-" + i;
        Date sss = formats.parse(s);
        String dd = formats.format(sss);
        list.add(dd);
    }
    return list;
}

From source file:com.fct.api.utils.IdcardUtils.java

/**
 * ???/*w ww.j  a  va  2  s.c  o  m*/
 *
 * @param idCard ?
 * @return 
 */
public static int getAgeByIdCard(String idCard) {
    if (idCard.length() == CHINA_ID_MIN_LENGTH) {
        idCard = conver15CardTo18(idCard);
    }
    String birthday = idCard.substring(6, 14);
    try {
        DateFormat idCardDateFormat = new SimpleDateFormat("yyyyMMdd");
        return getAgeByBirthday(idCardDateFormat.parse(birthday));
    } catch (ParseException ex) {
        return 0;
    }
}

From source file:com.cloud.bridge.util.EC2RestAuth.java

public static Calendar parseDateString(String created) {
    DateFormat formatter = null;
    Calendar cal = Calendar.getInstance();

    // -> for some unknown reason SimpleDateFormat does not properly handle the 'Z' timezone
    if (created.endsWith("Z"))
        created = created.replace("Z", "+0000");

    try {/*from   w w  w .ja v a  2 s. co m*/
        formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
        cal.setTime(formatter.parse(created));
        return cal;
    } catch (Exception e) {
    }

    try {
        formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        cal.setTime(formatter.parse(created));
        return cal;
    } catch (Exception e) {
    }

    // -> the time zone is GMT if not defined   
    try {
        formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        cal.setTime(formatter.parse(created));

        created = created + "+0000";
        formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        cal.setTime(formatter.parse(created));
        return cal;
    } catch (Exception e) {
    }

    // -> including millseconds?
    try {
        formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.Sz");
        cal.setTime(formatter.parse(created));
        return cal;
    } catch (Exception e) {
    }

    try {
        formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SZ");
        cal.setTime(formatter.parse(created));
        return cal;
    } catch (Exception e) {
    }

    // -> the CloudStack API used to return this format for some calls
    try {
        formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
        cal.setTime(formatter.parse(created));
        return cal;
    } catch (Exception e) {
    }

    return null;
}

From source file:com.krawler.spring.authHandler.authHandler.java

public static Date getCreatedonDate(DateFormat df, JSONObject jobj) throws JSONException {
    Date createdOnDate = null;/*from w  w w . ja v a2 s.  co  m*/
    if (jobj.has(Constants.createdon) && !StringUtil.isNullOrEmpty(jobj.getString(Constants.createdon))) {
        String createdOn = jobj.getString(Constants.createdon);
        if (createdOn != null) {
            try {
                createdOnDate = df.parse(createdOn);
            } catch (Exception e) {
                createdOnDate = authHandler.getCurrentDate();
            }
        }
    } else {
        createdOnDate = authHandler.getCurrentDate();
    }
    return createdOnDate;
}

From source file:arena.utils.XMLUtils.java

/**
 * Searches the node for content of type Long. If non-long content is found,
 * it logs a warning and returns null.//ww w.j  a v a 2 s. c  o m
 */
public static Date extractDateFromElement(Node element) {
    // Get the content and try to parse for a long
    String format = searchForAttribute(element, FORMAT_TAG);
    String nodeContent = extractStringFromElement(element);

    if (nodeContent == null) {
        return null;
    } else {
        try {
            if (format == null) {
                synchronized (sdfDefaultXML) {
                    return sdfDefaultXML.parse(nodeContent);
                }
            } else {
                DateFormat sdfXML = new SimpleDateFormat(format);
                synchronized (sdfDefaultXML) {
                    return sdfXML.parse(nodeContent);
                }
            }
        } catch (ParseException err) {
            LogFactory.getLog(XMLUtils.class)
                    .warn("Invalid data in date field: " + nodeContent + " (format=" + format + ")", err);
            return null;
        }
    }
}