Example usage for android.text.format DateFormat format

List of usage examples for android.text.format DateFormat format

Introduction

In this page you can find the example usage for android.text.format DateFormat format.

Prototype

public static CharSequence format(CharSequence inFormat, Calendar inDate) 

Source Link

Document

Given a format string and a java.util.Calendar object, returns a CharSequence containing the requested date.

Usage

From source file:net.mm2d.dmsexplorer.CdsDetailFragment.java

@Nullable
private static String getDate(@NonNull CdsObject object) {
    final String str = object.getValue(CdsObject.DC_DATE);
    final Date date = CdsObject.parseDate(str);
    if (date == null) {
        return null;
    }//  w  w  w.jav  a2  s. co  m
    if (str.length() <= 10) {
        return DateFormat.format("yyyy/MM/dd (E)", date).toString();
    }
    return DateFormat.format("yyyy/M/d (E) kk:mm:ss", date).toString();
}

From source file:org.pixmob.freemobile.netstat.SyncService.java

private void run(Intent intent, final SQLiteDatabase db) throws Exception {
    final long now = dateAtMidnight(System.currentTimeMillis());

    Log.i(TAG, "Initializing statistics before uploading");

    final LongSparseArray<DailyStat> stats = new LongSparseArray<DailyStat>(15);
    final Set<Long> uploadedStats = new HashSet<Long>(15);
    final long statTimestampStart = now - 7 * DAY_IN_MILLISECONDS;

    // Get pending uploads.
    Cursor c = db.query("daily_stat", new String[] { "stat_timestamp", "orange", "free_mobile", "sync" },
            "stat_timestamp>=? AND stat_timestamp<?",
            new String[] { String.valueOf(statTimestampStart), String.valueOf(now) }, null, null, null);
    try {//  ww w  .j ava  2 s.  c  o  m
        while (c.moveToNext()) {
            final long d = c.getLong(0);
            final int sync = c.getInt(3);
            if (SYNC_UPLOADED == sync) {
                uploadedStats.add(d);
            } else if (SYNC_PENDING == sync) {
                final DailyStat s = new DailyStat();
                s.orange = c.getInt(1);
                s.freeMobile = c.getInt(2);
                stats.put(d, s);
            }
        }
    } finally {
        c.close();
    }

    // Compute missing uploads.
    final ContentValues cv = new ContentValues();
    db.beginTransaction();
    try {
        for (long d = statTimestampStart; d < now; d += DAY_IN_MILLISECONDS) {
            if (stats.get(d) == null && !uploadedStats.contains(d)) {
                final DailyStat s = computeDailyStat(d);
                cv.put("stat_timestamp", d);
                cv.put("orange", s.orange);
                cv.put("free_mobile", s.freeMobile);
                cv.put("sync", SYNC_PENDING);
                db.insertOrThrow("daily_stat", null, cv);
                stats.put(d, s);
            }
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }

    // Delete old statistics.
    if (DEBUG) {
        Log.d(TAG, "Cleaning up upload database");
    }
    db.delete("daily_stat", "stat_timestamp<?", new String[] { String.valueOf(statTimestampStart) });

    // Check if there are any statistics to upload.
    final int statsLen = stats.size();
    if (statsLen == 0) {
        Log.i(TAG, "Nothing to upload");
        return;
    }

    // Check if the remote server is up.
    final HttpClient client = createHttpClient();
    try {
        client.head(createServerUrl(null)).execute();
    } catch (HttpClientException e) {
        Log.w(TAG, "Remote server is not available: cannot upload statistics", e);
        return;
    }

    // Upload statistics.
    Log.i(TAG, "Uploading statistics");
    final JSONObject json = new JSONObject();
    final String deviceId = getDeviceId();
    final boolean deviceWasRegistered = intent.getBooleanExtra(EXTRA_DEVICE_REG, false);
    for (int i = 0; i < statsLen; ++i) {
        final long d = stats.keyAt(i);
        final DailyStat s = stats.get(d);

        try {
            json.put("timeOnOrange", s.orange);
            json.put("timeOnFreeMobile", s.freeMobile);
        } catch (JSONException e) {
            final IOException ioe = new IOException("Failed to prepare statistics upload");
            ioe.initCause(e);
            throw ioe;
        }

        final String url = createServerUrl(
                "/device/" + deviceId + "/daily/" + DateFormat.format("yyyyMMdd", d));
        if (DEBUG) {
            Log.d(TAG, "Uploading statistics for " + DateUtils.formatDate(d) + " to: " + url);
        }

        final byte[] rawJson = json.toString().getBytes("UTF-8");
        try {
            client.post(url).content(rawJson, "application/json")
                    .expect(HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_NOT_FOUND)
                    .to(new HttpResponseHandler() {
                        @Override
                        public void onResponse(HttpResponse response) throws Exception {
                            final int sc = response.getStatusCode();
                            if (HttpURLConnection.HTTP_NOT_FOUND == sc) {
                                // Check if the device has just been
                                // registered.
                                if (deviceWasRegistered) {
                                    throw new IOException("Failed to upload statistics");
                                } else {
                                    // Got 404: the device does not exist.
                                    // We need to register this device.
                                    registerDevice(deviceId);

                                    // Restart this service.
                                    startService(new Intent(getApplicationContext(), SyncService.class)
                                            .putExtra(EXTRA_DEVICE_REG, true));
                                }
                            } else if (HttpURLConnection.HTTP_OK == sc) {
                                // Update upload database.
                                cv.clear();
                                cv.put("sync", SYNC_UPLOADED);
                                db.update("daily_stat", cv, "stat_timestamp=?",
                                        new String[] { String.valueOf(d) });

                                if (DEBUG) {
                                    Log.d(TAG, "Upload done for " + DateUtils.formatDate(d));
                                }
                            }
                        }
                    }).execute();
        } catch (HttpClientException e) {
            final IOException ioe = new IOException("Failed to send request with statistics");
            ioe.initCause(e);
            throw ioe;
        }
    }
}

From source file:alaindc.crowdroid.SendIntentService.java

private String getDate(long timestamp) {
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(timestamp);// www  .  ja v a2s . c o  m
    String date = DateFormat.format("yyyy/MM/dd HH:mm:ss", cal).toString();
    return date;
}

From source file:net.mm2d.dmsexplorer.CdsDetailFragment.java

@Nullable
private static String getSchedule(@NonNull CdsObject object) {
    final Date start = object.getDateValue(CdsObject.UPNP_SCHEDULED_START_TIME);
    final Date end = object.getDateValue(CdsObject.UPNP_SCHEDULED_END_TIME);
    if (start == null || end == null) {
        return null;
    }//  w w w  . j  a  va  2s.  c  om
    final String startString = DateFormat.format("yyyy/M/d (E) kk:mm", start).toString();
    final String endString;
    if (end.getTime() - start.getTime() > 12 * 3600 * 1000) {
        endString = DateFormat.format("yyyy/M/d (E) kk:mm", end).toString();
    } else {
        endString = DateFormat.format("kk:mm", end).toString();
    }
    return startString + "  " + endString;
}

From source file:com.mEmoZz.qrgen.MainActivity.java

public void mStream() {
    String fileName;//from ww  w  . j  a  v a 2s.c  o m

    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/QRCodes");

    myDir.mkdirs();

    Date d = new Date();
    CharSequence s = DateFormat.format("MM-dd-yy hh-mm-ss", d.getTime());

    fileName = "QR-" + s + ".png";

    File file = new File(myDir, fileName);

    try {
        FileOutputStream out = new FileOutputStream(file);
        bm.compress(Bitmap.CompressFormat.PNG, 90, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(getApplicationContext(), "I/O error", Toast.LENGTH_SHORT).show();
    }

    Toast.makeText(getApplicationContext(), "Saved to:\n \\QRCodes\\" + fileName, Toast.LENGTH_LONG).show();

}

From source file:com.zegoggles.smssync.service.SmsBackupService.java

private void scheduleNextBackup(BackupState state) {
    if (state.backupType == REGULAR && getPreferences().isUseOldScheduler()) {
        final Job nextSync = getBackupJobs().scheduleRegular();
        if (nextSync != null) {
            JobTrigger.ExecutionWindowTrigger trigger = (JobTrigger.ExecutionWindowTrigger) nextSync
                    .getTrigger();/*from  w w  w .j  av a2s  . c om*/
            Date date = new Date(System.currentTimeMillis() + (trigger.getWindowStart() * 1000));
            appLog(R.string.app_log_scheduled_next_sync, DateFormat.format("kk:mm", date));
        } else {
            appLog(R.string.app_log_no_next_sync);
        }
    } // else job already persisted
}

From source file:de.ub0r.android.websms.connector.innosend.ConnectorInnosend.java

/**
 * Send data.//from   w  ww.ja  v  a2s  . c o m
 * 
 * @param context
 *            Context
 * @param command
 *            ConnectorCommand
 * @param updateFree
 *            update free sms
 * @throws IOException
 *             IOException
 */
private void sendData(final Context context, final ConnectorCommand command, final boolean updateFree)
        throws IOException {
    // get Connection
    final ConnectorSpec cs = this.getSpec(context);
    final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
    final StringBuilder url = new StringBuilder(URL);
    final ArrayList<BasicNameValuePair> d = // .
            new ArrayList<BasicNameValuePair>();
    final String text = command.getText();
    if (text != null && text.length() > 0) {
        final String subCon = command.getSelectedSubConnector();
        if (subCon.equals(ID_FREE)) {
            url.append("free.php");
            d.add(new BasicNameValuePair("app", "1"));
            d.add(new BasicNameValuePair("was", "iphone"));
        } else {
            url.append("sms.php");
        }
        d.add(new BasicNameValuePair("text", text));
        if (subCon.equals(ID_W_SENDER)) {
            d.add(new BasicNameValuePair("type", "4"));
            if (text.length() > MAX_LENGTH) {
                d.add(new BasicNameValuePair("maxi", "1"));
            }
        } else if (subCon.equals(ID_WO_SENDER)) {
            d.add(new BasicNameValuePair("type", "2"));
            if (text.length() > MAX_LENGTH) {
                throw new WebSMSException(context, R.string.error_length);
            }
        } else {
            d.add(new BasicNameValuePair("type", "3"));
            if (text.length() > MAX_LENGTH) {
                throw new WebSMSException(context, R.string.error_length);
            }
        }
        d.add(new BasicNameValuePair("empfaenger",
                Utils.joinRecipientsNumbers(command.getRecipients(), ",", true)));

        final String customSender = command.getCustomSender();
        if (customSender == null) {
            d.add(new BasicNameValuePair("absender", Utils.international2national(command.getDefPrefix(),
                    Utils.getSender(context, command.getDefSender()))));
        } else {
            d.add(new BasicNameValuePair("absender", customSender));
        }
        final String rm = p.getString(PREFS_RETMAIL, "");
        if (rm != null && rm.length() > 2) {
            d.add(new BasicNameValuePair("reply_email", rm));
            d.add(new BasicNameValuePair("reply", "1"));
        }

        if (command.getFlashSMS()) {
            d.add(new BasicNameValuePair("flash", "1"));
        }
        long sendLater = command.getSendLater();
        if (sendLater > 0) {
            if (sendLater <= 0) {
                sendLater = System.currentTimeMillis();
            }
            d.add(new BasicNameValuePair("termin", DateFormat.format(DATEFORMAT, sendLater).toString()));
        }
    } else {
        if (updateFree) {
            url.append("free.php");
            d.add(new BasicNameValuePair("app", "1"));
            d.add(new BasicNameValuePair("was", "iphone"));
        } else {
            url.append("konto.php");
        }
    }
    d.add(new BasicNameValuePair("id", p.getString(Preferences.PREFS_USER, "")));
    d.add(new BasicNameValuePair("pw", p.getString(Preferences.PREFS_PASSWORD, "")));
    HttpOptions o = new HttpOptions();
    o.url = url.toString();
    o.addFormParameter(d);
    o.trustAll = true;
    HttpResponse response = Utils.getHttpClient(o);
    int resp = response.getStatusLine().getStatusCode();
    if (resp != HttpURLConnection.HTTP_OK) {
        throw new WebSMSException(context, R.string.error_http, " " + resp);
    }
    String htmlText = Utils.stream2str(response.getEntity().getContent()).trim();
    int i = htmlText.indexOf(',');
    if (i > 0 && !updateFree) {
        cs.setBalance(htmlText.substring(0, i + 3) + "\u20AC");
    } else {
        i = htmlText.indexOf("<br>");
        int ret;
        Log.d(TAG, url.toString());
        if (i < 0) {
            ret = Integer.parseInt(htmlText);
            if (!updateFree) {
                ConnectorInnosend.checkReturnCode(context, ret);
            }
        } else {
            ret = Integer.parseInt(htmlText.substring(0, i));
            ConnectorInnosend.checkReturnCode(context, cs, ret, htmlText.substring(i + 4).trim(), !updateFree);
        }
    }
}

From source file:com.renard.ocr.OCRActivity.java

private File saveImage(Pix p) throws IOException {
    CharSequence id = DateFormat.format("ssmmhhddMMyy", new Date(System.currentTimeMillis()));
    return Util.savePixToSD(p, id.toString());
}

From source file:org.opendatakit.common.android.utilities.WebUtils.java

private void setOpenRosaHeaders(HttpRequest req) {
    req.setHeader(OPEN_ROSA_VERSION_HEADER, OPEN_ROSA_VERSION);
    g.setTime(new Date());
    req.setHeader(DATE_HEADER, DateFormat.format("E, dd MMM yyyy hh:mm:ss zz", g).toString());
}

From source file:org.pixmob.freemobile.netstat.SyncServiceTesting.java

private void run(Intent intent, final SQLiteDatabase db) throws Exception {
    final long now = dateAtMidnight(System.currentTimeMillis());

    Log.i(TAG, "Initializing statistics before uploading");

    final LongSparseArray<DailyStat> stats = new LongSparseArray<>(15);
    final Set<Long> uploadedStats = new HashSet<>(15);
    final long statTimestampStart = now - 7 * DAY_IN_MILLISECONDS;

    // Get pending uploads.
    Cursor pendingUploadsCursor = null;
    try {// w ww.j a va  2  s .  com
        pendingUploadsCursor = db.query("daily_stat_testing",
                new String[] { "stat_timestamp", "orange", "free_mobile", "free_mobile_3g", "free_mobile_4g",
                        "free_mobile_femtocell", "sync" },
                "stat_timestamp>=? AND stat_timestamp<?",
                new String[] { String.valueOf(statTimestampStart), String.valueOf(now) }, null, null, null);
        while (pendingUploadsCursor.moveToNext()) {
            final long d = pendingUploadsCursor.getLong(0);
            final int sync = pendingUploadsCursor.getInt(6);
            if (SYNC_UPLOADED == sync) {
                uploadedStats.add(d);
            } else if (SYNC_PENDING == sync) {
                final DailyStat s = new DailyStat();
                s.orange = pendingUploadsCursor.getInt(1);
                s.freeMobile = pendingUploadsCursor.getInt(2);
                s.freeMobile3G = pendingUploadsCursor.getInt(3);
                s.freeMobile4G = pendingUploadsCursor.getInt(4);
                s.freeMobileFemtocell = pendingUploadsCursor.getInt(5);
                stats.put(d, s);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    } finally {
        try {
            if (pendingUploadsCursor != null)
                pendingUploadsCursor.close();
        } catch (Exception e) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    }

    // Compute missing uploads.
    final ContentValues cv = new ContentValues();
    db.beginTransaction();
    try {
        for (long d = statTimestampStart; d < now; d += DAY_IN_MILLISECONDS) {
            if (stats.get(d) == null && !uploadedStats.contains(d)) {
                final DailyStat s = computeDailyStat(d);
                cv.put("stat_timestamp", d);
                cv.put("orange", s.orange);
                cv.put("free_mobile", s.freeMobile);
                cv.put("free_mobile_3g", s.freeMobile3G);
                cv.put("free_mobile_4g", s.freeMobile4G);
                cv.put("free_mobile_femtocell", s.freeMobileFemtocell);
                cv.put("sync", SYNC_PENDING);
                db.insertOrThrow("daily_stat_testing", null, cv);
                stats.put(d, s);
            }
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }

    // Delete old statistics.
    if (DEBUG) {
        Log.d(TAG, "Cleaning up upload database");
    }
    db.delete("daily_stat_testing", "stat_timestamp<?", new String[] { String.valueOf(statTimestampStart) });

    // Check if there are any statistics to upload.
    final int statsLen = stats.size();
    if (statsLen == 0) {
        Log.i(TAG, "Nothing to upload");
        return;
    }

    // Check if the remote server is up.
    final HttpClient client = createHttpClient();
    try {
        client.head(createServerUrl(null)).execute();
    } catch (HttpClientException e) {
        Log.w(TAG, "Remote server is not available: cannot upload statistics", e);
        return;
    }

    // Upload statistics.
    Log.i(TAG, "Uploading statistics");
    final JSONObject json = new JSONObject();
    final String deviceId = getDeviceId();
    final boolean deviceWasRegistered = intent.getBooleanExtra(EXTRA_DEVICE_REG, false);
    for (int i = 0; i < statsLen; ++i) {
        final long d = stats.keyAt(i);
        final DailyStat s = stats.get(d);

        try {
            json.put("timeOnOrange", s.orange);
            json.put("timeOnFreeMobile", s.freeMobile);
            json.put("timeOnFreeMobile3g", s.freeMobile3G);
            json.put("timeOnFreeMobile4g", s.freeMobile4G);
            json.put("timeOnFreeMobileFemtocell", s.freeMobileFemtocell);
        } catch (JSONException e) {
            final IOException ioe = new IOException("Failed to prepare statistics upload");
            ioe.initCause(e);
            throw ioe;
        }

        final String url = createServerUrl(
                "/device/" + deviceId + "/daily/" + DateFormat.format("yyyyMMdd", d));
        if (DEBUG) {
            Log.d(TAG, "Uploading statistics for " + DateUtils.formatDate(d) + " to: " + url);
        }

        final byte[] rawJson = json.toString().getBytes("UTF-8");
        try {
            client.post(url).content(rawJson, "application/json")
                    .expect(HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_NOT_FOUND)
                    .to(new HttpResponseHandler() {
                        @Override
                        public void onResponse(HttpResponse response) throws Exception {
                            final int sc = response.getStatusCode();
                            if (HttpURLConnection.HTTP_NOT_FOUND == sc) {
                                // Check if the device has just been
                                // registered.
                                if (deviceWasRegistered) {
                                    throw new IOException("Failed to upload statistics");
                                } else {
                                    // Got 404: the device does not exist.
                                    // We need to register this device.
                                    registerDevice(deviceId);

                                    // Restart this service.
                                    startService(new Intent(getApplicationContext(), SyncServiceTesting.class)
                                            .putExtra(EXTRA_DEVICE_REG, true));
                                }
                            } else if (HttpURLConnection.HTTP_OK == sc) {
                                // Update upload database.
                                cv.clear();
                                cv.put("sync", SYNC_UPLOADED);
                                db.update("daily_stat_testing", cv, "stat_timestamp=?",
                                        new String[] { String.valueOf(d) });

                                if (DEBUG) {
                                    Log.d(TAG, "Upload done for " + DateUtils.formatDate(d));
                                }
                            }
                        }
                    }).execute();
        } catch (HttpClientException e) {
            final IOException ioe = new IOException("Failed to send request with statistics");
            ioe.initCause(e);
            throw ioe;
        }
    }
}