Example usage for java.util Date parse

List of usage examples for java.util Date parse

Introduction

In this page you can find the example usage for java.util Date parse.

Prototype

@Deprecated
public static long parse(String s) 

Source Link

Document

Attempts to interpret the string s as a representation of a date and time.

Usage

From source file:org.flockdata.transform.ExpressionHelper.java

public static Long parseDate(ColumnDefinition colDef, String value) {
    if (value == null || value.equals(""))
        return null;
    if (colDef.isDateEpoc()) {
        return Long.parseLong(value) * 1000;
    }/*from www  .j av a 2  s. c  o  m*/

    if (colDef.getDateFormat() == null || colDef.getDateFormat().equalsIgnoreCase("automatic")) {
        try {
            return Date.parse(value);
        } catch (IllegalArgumentException e) {
            // Try other formats
        }
    }
    if (colDef.getDateFormat() != null && colDef.getDateFormat().equalsIgnoreCase("timestamp")) {
        try {
            return Timestamp.valueOf(value).getTime();
        } catch (IllegalArgumentException e) {
            // attempt other conversions
        }
    }

    if (NumberUtils.isDigits(value)) // plain old java millis
        return Long.parseLong(value);

    // Custom Date formats
    String tz = colDef.getTimeZone();
    if (tz == null)
        tz = TimeZone.getDefault().getID();

    try {

        // Try first as DateTime
        return new SimpleDateFormat(colDef.getDateFormat()).parse(value).getTime();
    } catch (DateTimeParseException | IllegalArgumentException | ParseException e) {
        // Just a plain date
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern(colDef.getDateFormat(), Locale.ENGLISH);
        LocalDate date = LocalDate.parse(value, pattern);
        return new DateTime(date.toString(), DateTimeZone.forID(tz)).getMillis();
    }
}

From source file:com.sangupta.jerry.http.WebResponse.java

/**
* Return the last modified date as a long value
* 
* @return the millis timestamp representing the last modified header, or
*         <code>-1</code> if the header is not present or cannot be parsed
*         successfully//from w  ww .j av  a2s. co  m
*/
public long getLastModified() {
    String headerValue = getHeader(HttpHeaders.LAST_MODIFIED);
    if (headerValue != null) {
        try {
            return Date.parse(headerValue);
        } catch (Exception e) {
            // eat this up
        }
    }

    return -1;
}

From source file:com.madrobot.di.Converter.java

/**
 * Converts a {@link String} value to specified type, if possible.
 * //from  ww w .  j a va  2s . com
 * @param raw
 *            Raw, string value, to be converted
 * @param clz
 *            Target type to be converted to
 * @return Converted value, if converstion was possible, null otherwise
 * @throws NumberFormatException
 *             If the value was not in correct format, while converting to numeric type
 * @throws RuntimeException
 *             If the value was not in correct format, while converting to Date or Boolean type
 */
public static Object convertTo(final String raw, final Class<?> clz) {
    Object value = null;
    if (clzTypeKeyMap.containsKey(clz)) {
        final int code = clzTypeKeyMap.get(clz);
        switch (code) {
        case TYPE_STRING:
            value = raw;
            break;
        case TYPE_SHORT:
            value = Short.parseShort(raw);
            break;
        case TYPE_INT:
            value = Integer.parseInt(raw);
            break;
        case TYPE_LONG:
            value = Long.parseLong(raw);
            break;
        case TYPE_CHAR:
            if ((raw != null) && (raw.length() > 0)) {
                value = raw.charAt(0);
            } else {
                value = '\0';
            }
            break;
        case TYPE_FLOAT:
            value = Float.parseFloat(raw);
            break;
        case TYPE_DOUBLE:
            value = Double.parseDouble(raw);
            break;
        case TYPE_BOOLEAN:
            value = Boolean.parseBoolean(raw);
            break;
        case TYPE_DATE:
            value = Date.parse(raw);
            break;
        default:
            break;
        }
    }
    return value;
}

From source file:org.blanco.techmun.android.cproviders.EventosFetcher.java

public Eventos fetchEventos(Long mesaId) {
    Eventos result = null;// w  w w.j  a v  a2s .c om
    //Check the preference to reload eventos list and the expiration of the cache
    boolean forceRefresh = PreferenceManager.getDefaultSharedPreferences(context)
            .getBoolean("force_eventos_refresh_" + mesaId, true);
    if (!forceRefresh) {
        long lastRefresh = PreferenceManager.getDefaultSharedPreferences(context)
                .getLong("eventos_last_refresh", -1);
        //if the last refresh ocurred no more than 3 minutes load from cache
        long diff = System.currentTimeMillis() - lastRefresh;
        if (diff < 180000) {
            result = tryToLoadFromCache(context, mesaId);
            if (result != null && !result.getEventos().isEmpty()) {
                return result;
            }
        }
    }
    result = new Eventos();
    HttpGet request = new HttpGet(
            TechMunContentProvider.MESAS_REST_SERVICE_BSAE_URI + "/mesas/" + mesaId + "/eventos");
    //      Evento e = new Evento(); e.setDescripcion("evento de prueba"); 
    //      e.setFecha(new Date(System.currentTimeMillis())); e.setId(1L); e.setMesaId(1L); 
    //      e.setTitulo("evento de prueba");
    //      result.getEventos().add(e);
    //      return result;
    HttpResponse response = null;
    try {
        response = httpClient.execute(request);
        if (response.getStatusLine().getStatusCode() == 200) {
            JSONArray jsonEventos = XmlParser.parseJSONArrayFromHttpEntity(response.getEntity());
            for (int i = 0; i < jsonEventos.length(); i++) {
                Long id = jsonEventos.getJSONObject(i).getLong("id");
                String titulo = jsonEventos.getJSONObject(i).getString("titulo");
                String desc = jsonEventos.getJSONObject(i).getString("descripcion");
                String fecha = jsonEventos.getJSONObject(i).getString("fecha");
                Evento e = new Evento();
                e.setId(id);
                e.setTitulo(titulo);
                e.setMesaId(mesaId);
                e.setFecha(new Date(Date.parse(fecha)));
                e.setDescripcion(desc);
                result.getEventos().add(e);
            }
        }
    } catch (ClientProtocolException ex) {
        Log.e("techmun", "Error retrieving eventos from server", ex);
    } catch (IOException ex) {
        Log.e("techmun", "Error reading eventos from server", ex);
    } catch (Exception ex) {
        Log.e("techmun", "Error retrieving eventos from server", ex);
    }
    if (result != null) {
        saveOnCache(context, result, mesaId);
    }
    return result;
}

From source file:com.xorcode.andtweet.FriendTimeline.java

/**
 * Insert a row from a JSONObject./*from w  w  w . j  a va  2 s. c om*/
 * 
 * @param jo
 * @return
 * @throws JSONException
 * @throws SQLiteConstraintException
 */
public Uri insertFromJSONObject(JSONObject jo) throws JSONException, SQLiteConstraintException {
    ContentValues values = new ContentValues();

    // Construct the Uri to existing record
    Long lTweetId = Long.parseLong(jo.getString("id"));
    Uri aTweetUri = ContentUris.withAppendedId(mContentUri, lTweetId);

    String message = Html.fromHtml(jo.getString("text")).toString();

    try {
        // TODO: Unify databases!
        switch (mTimelineType) {
        case AndTweetDatabase.Tweets.TIMELINE_TYPE_FRIENDS:
        case AndTweetDatabase.Tweets.TIMELINE_TYPE_MENTIONS:
            JSONObject user;
            user = jo.getJSONObject("user");

            values.put(AndTweetDatabase.Tweets._ID, lTweetId.toString());
            values.put(AndTweetDatabase.Tweets.AUTHOR_ID, user.getString("screen_name"));

            values.put(AndTweetDatabase.Tweets.MESSAGE, message);
            values.put(AndTweetDatabase.Tweets.SOURCE, jo.getString("source"));
            values.put(AndTweetDatabase.Tweets.TWEET_TYPE, mTimelineType);
            values.put(AndTweetDatabase.Tweets.IN_REPLY_TO_STATUS_ID, jo.getString("in_reply_to_status_id"));
            values.put(AndTweetDatabase.Tweets.IN_REPLY_TO_AUTHOR_ID, jo.getString("in_reply_to_screen_name"));
            values.put(AndTweetDatabase.Tweets.FAVORITED, jo.getBoolean("favorited") ? 1 : 0);
            break;
        case AndTweetDatabase.Tweets.TIMELINE_TYPE_MESSAGES:
            values.put(AndTweetDatabase.DirectMessages._ID, lTweetId.toString());
            values.put(AndTweetDatabase.DirectMessages.AUTHOR_ID, jo.getString("sender_screen_name"));
            values.put(AndTweetDatabase.DirectMessages.MESSAGE, message);
            break;
        }

        Long created = Date.parse(jo.getString("created_at"));
        values.put(AndTweetDatabase.Tweets.SENT_DATE, created);
    } catch (Exception e) {
        Log.e(TAG, "insertFromJSONObject: " + e.toString());
    }

    if ((mContentResolver.update(aTweetUri, values, null, null)) == 0) {
        // There was no such row so add new one
        mContentResolver.insert(mContentUri, values);
        mNewTweets++;
        switch (mTimelineType) {
        case AndTweetDatabase.Tweets.TIMELINE_TYPE_FRIENDS:
        case AndTweetDatabase.Tweets.TIMELINE_TYPE_MENTIONS:
            if (mTu.getUsername().equals(jo.getString("in_reply_to_screen_name"))
                    || message.contains("@" + mTu.getUsername())) {
                mReplies++;
            }
        }
    }
    return aTweetUri;
}

From source file:org.blanco.techmun.android.cproviders.MensajesFetcher.java

public List<Mensaje> getMensajes() {
    List<Mensaje> result = null;

    //Do not force the cache load first in order to know if the cache is old or not
    //   result = tryToLoadFromCache(context, false);
    //   if (result != null){
    //      //If loaded from cache
    //      return result;
    //   }//from  ww w .ja v a 2 s  . c  om

    HttpResponse response;
    boolean retrieved = true;
    try {
        result = new ArrayList<Mensaje>();
        HttpGet req = new HttpGet(TechMunContentProvider.MESAS_REST_SERVICE_BSAE_URI + "/mensajes");
        response = client.execute(req);
        HttpEntity entity = response.getEntity();
        JSONArray mensajes = XmlParser.parseJSONArrayFromHttpEntity(entity);
        for (int i = 0; i < mensajes.length(); i++) {
            JSONObject joMensaje = mensajes.getJSONObject(i);
            String sMensaje = joMensaje.getString("mensaje");
            long id = joMensaje.getLong("id");
            String sFecha = joMensaje.getString("fecha");
            Usuario autor = null;
            if (joMensaje.has("autor")) {
                JSONObject joUsuario = joMensaje.getJSONObject("autor");
                String saNombre = joUsuario.getString("nombre");
                String saCorreo = joUsuario.getString("correo");
                autor = new Usuario(saNombre, saCorreo);
            }
            Mensaje mensaje = new Mensaje(sMensaje, autor);
            mensaje.setFecha(new Date(Date.parse(sFecha)));
            mensaje.setId(id);
            //try to load the foto of the mensaje
            String encoded_foto = joMensaje.getString("encoded_foto");
            if (encoded_foto != null && !encoded_foto.equals("")) {
                byte foto[] = Base64Coder.decode(encoded_foto.toCharArray());
                mensaje.setFoto(BitmapFactory.decodeByteArray(foto, 0, foto.length));
            }

            result.add(mensaje);
        }
    } catch (Exception e) {
        Log.e("techmun2011", "Error Retrieving Mensajes from internet", e);
        retrieved = false;
    }
    //If there is an error with the connection try to load mensajes from cache
    if (!retrieved) {
        result = tryToLoadFromCache(context, true);
        return result;
    }
    //saveOnCache(context, result);
    return result;
}

From source file:jp.co.rakuten.rakutenvideoplayer.base.BaseActivity.java

/***
 * Check time before 2 week//  ww w  .  j  ava 2 s  .c  om
 * 
 * @param date
 * @return boolean
 */
@SuppressLint("SimpleDateFormat")
private boolean checkTimeBeforeTwoWeek(String date) {
    DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
    String currentDateandTime = formatter.format(new Date());
    @SuppressWarnings("deprecation")
    long diff = Date.parse(currentDateandTime) - Date.parse(date);
    float dayCount = (float) diff / (24 * 60 * 60 * 1000);
    if (dayCount >= 14.0)
        return true;
    else
        return false;
}

From source file:com.amansoni.tripbook.activity.AddItemActivity.java

private boolean validate() {
    if (mTripName.getText().toString().length() == 0) {
        String message = getResources().getString(R.string.error_field_required);
        mTripName.setError(message, getResources().getDrawable(R.drawable.ic_action_error));
        mTripName.requestFocus();// www  .  j ava  2  s .c o m
        return false;
    }
    if (mStartDatePicker.getText().toString().length() == 0) {
        String message = getResources().getString(R.string.error_field_required);
        mStartDatePicker.setError(message, getResources().getDrawable(R.drawable.ic_action_error));
        mStartDatePicker.requestFocus();
        return false;
    }
    if (mItemType.equals(TripBookItem.TYPE_TRIP) && mEndDatePicker.getText().toString().length() == 0) {
        String message = getResources().getString(R.string.error_field_required);
        mEndDatePicker.setError(message, getResources().getDrawable(R.drawable.ic_action_error));
        mEndDatePicker.requestFocus();
        return false;
    }
    long startDate = Date.parse(mStartDatePicker.getText().toString());
    if (mEndDatePicker.getText().toString().length() > 0) {
        long endDate = Date.parse(mEndDatePicker.getText().toString());
        if (endDate < startDate) {
            String message = getResources().getString(R.string.enddate_before_startdate);
            mEndDatePicker.setError(message, getResources().getDrawable(R.drawable.ic_action_error));
            mEndDatePicker.requestFocus();
            return false;
        }
    }
    return true;
}

From source file:org.andstatus.app.net.social.Connection.java

/**
 * @return Unix time. Returns 0 in a case of an error
 *///from w ww  .ja v a  2  s . c om
public long parseDate(String stringDate) {
    if (TextUtils.isEmpty(stringDate)) {
        return 0;
    }
    long unixDate = 0;
    String[] formats = { "", "E MMM d HH:mm:ss Z yyyy", "E, d MMM yyyy HH:mm:ss Z" };
    for (String format : formats) {
        if (TextUtils.isEmpty(format)) {
            try {
                unixDate = Date.parse(stringDate);
            } catch (IllegalArgumentException e) {
                MyLog.ignored(this, e);
            }
        } else {
            DateFormat dateFormat1 = new SimpleDateFormat(format, Locale.ENGLISH);
            try {
                unixDate = dateFormat1.parse(stringDate).getTime();
            } catch (ParseException e) {
                MyLog.ignored(this, e);
            }
        }
        if (unixDate != 0) {
            break;
        }
    }
    if (unixDate == 0) {
        MyLog.d(this, "Failed to parse the date: '" + stringDate + "'");
    }
    return unixDate;
}

From source file:com.sina.weibo.sdk.demo.sample.activity.TestFragment.java

@SuppressWarnings("deprecation")
public String dealTime(String time)// ???
{
    Date now = new Date();
    long lnow = now.getTime() / 1000;

    long ldate = Date.parse(time) / 1000;
    Date date = new Date(ldate);

    if ((lnow - ldate) < 60)
        return (lnow - ldate) + "?";
    else if ((lnow - ldate) < 60 * 60)
        return ((lnow - ldate) / 60) + "?";
    else//from w w w .  j a  va 2s  .co  m
        return time.substring(4, 16);
}