Example usage for android.text.format DateUtils DAY_IN_MILLIS

List of usage examples for android.text.format DateUtils DAY_IN_MILLIS

Introduction

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

Prototype

long DAY_IN_MILLIS

To view the source code for android.text.format DateUtils DAY_IN_MILLIS.

Click Source Link

Usage

From source file:Main.java

public static String formatRelativeDate(Context dateContext, Date date) {
    return DateUtils.getRelativeDateTimeString(dateContext, date.getTime(), DateUtils.MINUTE_IN_MILLIS,
            DateUtils.DAY_IN_MILLIS * 2, 0).toString();
}

From source file:Main.java

/**
 * Get formatted time.//from  w w w .j a  v  a 2  s . com
 *
 * @param publishedTime The published time in millis.
 *
 * @return The formatted time.
 */
static public String getFormattedTime(long publishedTime) {
    // This is copied from RecentCallsListActivity.java

    long now = System.currentTimeMillis();

    // Set the date/time field by mixing relative and absolute times.
    int flags = DateUtils.FORMAT_ABBREV_ALL;

    if (!DateUtils.isToday(publishedTime)) {
        // DateUtils.getRelativeTimeSpanString doesn't consider the nature
        // days comparing with DateUtils.getRelativeDayString. Override the
        // real date to implement the requirement.

        Time time = new Time();
        time.set(now);
        long gmtOff = time.gmtoff;
        int days = Time.getJulianDay(publishedTime, gmtOff) - Time.getJulianDay(now, gmtOff);

        // Set the delta from now to get the correct display
        publishedTime = now + days * DateUtils.DAY_IN_MILLIS;
    } else if (publishedTime > now && (publishedTime - now) < DateUtils.HOUR_IN_MILLIS) {
        // Avoid e.g. "1 minute left" when publish time is "07:00" and
        // current time is "06:58"
        publishedTime += DateUtils.MINUTE_IN_MILLIS;
    }

    return (DateUtils.getRelativeTimeSpanString(publishedTime, now, DateUtils.MINUTE_IN_MILLIS, flags))
            .toString();
}

From source file:can.yrt.onebusaway.QueryUtils.java

static protected CursorLoader newRecentQuery(final Context context, final Uri uri, final String[] projection,
        final String accessTime, final String useCount) {
    // "Recently" means seven days in the past
    final long last = System.currentTimeMillis() - 7 * DateUtils.DAY_IN_MILLIS;
    Uri limit = uri.buildUpon().appendQueryParameter("limit", "20").build();

    String regionWhere = "";
    if (Application.get().getCurrentRegion() != null) {
        if (projection.equals(QueryUtils.StopList.Columns.PROJECTION)) {
            regionWhere = " AND " + StopList.getRegionWhere();
        } else if (projection.equals(QueryUtils.RouteList.Columns.PROJECTION)) {
            regionWhere = " AND " + RouteList.getRegionWhere();
        }//w w w  .  ja v  a2 s.co  m
    }

    return new CursorLoader(
            context, limit, projection, "((" + accessTime + " IS NOT NULL AND " + accessTime + " > " + last
                    + ") OR (" + useCount + " > 0))" + regionWhere,
            null, accessTime + " desc, " + useCount + " desc");
}

From source file:Main.java

public static int daysBetween(Date d1, Date d2) {
    return (int) ((d2.getTime() - d1.getTime()) / DateUtils.DAY_IN_MILLIS);
}

From source file:net.zionsoft.obadiah.model.utils.AppUpdateChecker.java

@Override
protected void onHandleIntent(Intent intent) {
    try {/*from   w  w w . j ava2  s  . co m*/
        // we only check if at least 24 hours is passed
        final SharedPreferences preferences = getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE);
        final long now = System.currentTimeMillis();
        final long lastCheckedTimestamp = preferences
                .getLong(Constants.PREF_KEY_CHECKED_APPLICATION_VERSION_TIMESTAMP, 0);
        if (now - lastCheckedTimestamp < DateUtils.DAY_IN_MILLIS) {
            return;
        }

        // we only check if the user has active WiFi or WiMAX
        final NetworkInfo networkInfo = ((ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE))
                .getActiveNetworkInfo();
        if (networkInfo == null || !networkInfo.isConnected()) {
            return;
        }
        final int networkType = networkInfo.getType();
        if (networkType != ConnectivityManager.TYPE_WIFI && networkType != ConnectivityManager.TYPE_WIMAX) {
            return;
        }

        final String response = new String(NetworkHelper.get(NetworkHelper.CLIENT_VERSION_URL), "UTF-8");
        final JSONObject versionObject = new JSONObject(response);
        final int latestVersion = versionObject.getInt("versionCode");
        final SharedPreferences.Editor editor = preferences.edit();
        if (latestVersion < preferences.getInt(Constants.PREF_KEY_CHECKED_APPLICATION_VERSION, 0)) {
            editor.putInt(Constants.PREF_KEY_CHECKED_APPLICATION_VERSION, latestVersion)
                    .putBoolean(Constants.PREF_KEY_ASKED_APPLICATION_UPDATE, false);
        }

        editor.putLong(Constants.PREF_KEY_CHECKED_APPLICATION_VERSION_TIMESTAMP, now).apply();
    } catch (Exception e) {
        Crashlytics.logException(e);
    }
}

From source file:com.f2prateek.foodbot.model.LogAdapter.java

@Override
public void bindView(View view, Context context, Cursor cursor) {
    LogEntry entry = new LogEntry(cursor);

    TextView calories = (TextView) view.findViewById(R.id.tv_label_calories);
    TextView description = (TextView) view.findViewById(R.id.tv_label_description);
    TextView date = (TextView) view.findViewById(R.id.tv_label_timestamp);

    calories.setText(entry.getCalories() + "");
    description.setText(entry.getDescription());
    date.setText(DateUtils.getRelativeTimeSpanString(entry.getDate(), System.currentTimeMillis(),
            DateUtils.DAY_IN_MILLIS));
}

From source file:com.twitter.sdk.android.tweetui.TweetDateUtils.java

/**
 * This method is not thread safe. It has been modified from the original to not rely on global
 * time state. If a timestamp is in the future we return it as an absolute date string. Within
 * the same second we return 0s/*from   ww w . ja v  a 2s  . c  om*/
 *
 * @param res resource
 * @param currentTimeMillis timestamp for offset
 * @param timestamp timestamp
 * @return the relative time string
 */
static String getRelativeTimeString(Resources res, long currentTimeMillis, long timestamp) {
    final long diff = currentTimeMillis - timestamp;
    if (diff >= 0) {
        if (diff < DateUtils.MINUTE_IN_MILLIS) { // Less than a minute ago
            final int secs = (int) (diff / 1000);
            return res.getQuantityString(R.plurals.tw__time_secs, secs, secs);
        } else if (diff < DateUtils.HOUR_IN_MILLIS) { // Less than an hour ago
            final int mins = (int) (diff / DateUtils.MINUTE_IN_MILLIS);
            return res.getQuantityString(R.plurals.tw__time_mins, mins, mins);
        } else if (diff < DateUtils.DAY_IN_MILLIS) { // Less than a day ago
            final int hours = (int) (diff / DateUtils.HOUR_IN_MILLIS);
            return res.getQuantityString(R.plurals.tw__time_hours, hours, hours);
        } else {
            final Calendar now = Calendar.getInstance();
            now.setTimeInMillis(currentTimeMillis);
            final Calendar c = Calendar.getInstance();
            c.setTimeInMillis(timestamp);
            final Date d = new Date(timestamp);

            if (now.get(Calendar.YEAR) == c.get(Calendar.YEAR)) {
                // Same year
                return RELATIVE_DATE_FORMAT.formatShortDateString(res, d);
            } else {
                // Outside of our year
                return RELATIVE_DATE_FORMAT.formatLongDateString(res, d);
            }
        }
    }
    return RELATIVE_DATE_FORMAT.formatLongDateString(res, new Date(timestamp));
}

From source file:gov.wa.wsdot.android.wsdot.service.CamerasSyncService.java

@Override
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;/*from   www.j a v a 2 s  .c  o  m*/
    long now = System.currentTimeMillis();
    boolean shouldUpdate = true;
    String responseString = "";

    /** 
     * Check the cache table for the last time data was downloaded. If we are within
     * the allowed time period, don't sync, otherwise get fresh data from the server.
     */
    try {
        cursor = resolver.query(Caches.CONTENT_URI, projection, Caches.CACHE_TABLE_NAME + " LIKE ?",
                new String[] { "cameras" }, null);

        if (cursor != null && cursor.moveToFirst()) {
            long lastUpdated = cursor.getLong(0);
            //long deltaDays = (now - lastUpdated) / DateUtils.DAY_IN_MILLIS;
            //Log.d(DEBUG_TAG, "Delta since last update is " + deltaDays + " day(s)");
            shouldUpdate = (Math.abs(now - lastUpdated) > (7 * DateUtils.DAY_IN_MILLIS));
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    // Ability to force a refresh of camera data.
    boolean forceUpdate = intent.getBooleanExtra("forceUpdate", false);

    if (shouldUpdate || forceUpdate) {
        List<Integer> starred = new ArrayList<Integer>();

        starred = getStarred();

        try {
            URL url = new URL(CAMERAS_URL);
            URLConnection urlConn = url.openConnection();

            BufferedInputStream bis = new BufferedInputStream(urlConn.getInputStream());
            GZIPInputStream gzin = new GZIPInputStream(bis);
            InputStreamReader is = new InputStreamReader(gzin);
            BufferedReader in = new BufferedReader(is);

            String jsonFile = "";
            String line;
            while ((line = in.readLine()) != null)
                jsonFile += line;
            in.close();

            JSONObject obj = new JSONObject(jsonFile);
            JSONObject result = obj.getJSONObject("cameras");
            JSONArray items = result.getJSONArray("items");
            List<ContentValues> cams = new ArrayList<ContentValues>();

            int numItems = items.length();
            for (int j = 0; j < numItems; j++) {
                JSONObject item = items.getJSONObject(j);
                ContentValues cameraData = new ContentValues();

                cameraData.put(Cameras.CAMERA_ID, item.getString("id"));
                cameraData.put(Cameras.CAMERA_TITLE, item.getString("title"));
                cameraData.put(Cameras.CAMERA_URL, item.getString("url"));
                cameraData.put(Cameras.CAMERA_LATITUDE, item.getString("lat"));
                cameraData.put(Cameras.CAMERA_LONGITUDE, item.getString("lon"));
                cameraData.put(Cameras.CAMERA_HAS_VIDEO, item.getString("video"));
                cameraData.put(Cameras.CAMERA_ROAD_NAME, item.getString("roadName"));

                if (starred.contains(Integer.parseInt(item.getString("id")))) {
                    cameraData.put(Cameras.CAMERA_IS_STARRED, 1);
                }

                cams.add(cameraData);
            }

            // Purge existing cameras covered by incoming data
            resolver.delete(Cameras.CONTENT_URI, null, null);
            // Bulk insert all the new cameras
            resolver.bulkInsert(Cameras.CONTENT_URI, cams.toArray(new ContentValues[cams.size()]));
            // Update the cache table with the time we did the update
            ContentValues values = new ContentValues();
            values.put(Caches.CACHE_LAST_UPDATED, System.currentTimeMillis());
            resolver.update(Caches.CONTENT_URI, values, Caches.CACHE_TABLE_NAME + " LIKE ?",
                    new String[] { "cameras" });

            responseString = "OK";
        } catch (Exception e) {
            Log.e(DEBUG_TAG, "Error: " + e.getMessage());
            responseString = e.getMessage();
        }
    } else {
        responseString = "NOP";
    }

    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction("gov.wa.wsdot.android.wsdot.intent.action.CAMERAS_RESPONSE");
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra("responseString", responseString);
    sendBroadcast(broadcastIntent);
}

From source file:com.cerema.cloud2.ui.dialog.ExpirationDatePickerDialogFragment.java

/**
 * {@inheritDoc}/*w  w w . ja v a 2 s  . c  o  m*/
 *
 * @return      A new dialog to let the user choose an expiration date that will be bound to a share link.
 */
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Load arguments
    mFile = getArguments().getParcelable(ARG_FILE);

    // Chosen date received as an argument must be later than tomorrow ; default to tomorrow in other case
    final Calendar chosenDate = Calendar.getInstance();
    long tomorrowInMillis = chosenDate.getTimeInMillis() + DateUtils.DAY_IN_MILLIS;
    long chosenDateInMillis = getArguments().getLong(ARG_CHOSEN_DATE_IN_MILLIS);
    if (chosenDateInMillis > tomorrowInMillis) {
        chosenDate.setTimeInMillis(chosenDateInMillis);
    } else {
        chosenDate.setTimeInMillis(tomorrowInMillis);
    }

    // Create a new instance of DatePickerDialog
    DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, chosenDate.get(Calendar.YEAR),
            chosenDate.get(Calendar.MONTH), chosenDate.get(Calendar.DAY_OF_MONTH));

    // Prevent days in the past may be chosen
    DatePicker picker = dialog.getDatePicker();
    picker.setMinDate(tomorrowInMillis - 1000);

    // Enforce spinners view; ignored by MD-based theme in Android >=5, but calendar is REALLY buggy
    // in Android < 5, so let's be sure it never appears (in tablets both spinners and calendar are
    // shown by default)
    picker.setCalendarViewShown(false);

    return dialog;
}

From source file:com.liferay.alerts.model.Alert.java

public String getFormattedTimestamp() {
    String formattedTimestamp;/* w w w  . jav a  2  s.  c  om*/
    long elapsedTime = System.currentTimeMillis() - _timestamp;

    if (elapsedTime < DateUtils.MINUTE_IN_MILLIS) {
        formattedTimestamp = String.format("%ds", TimeUnit.MILLISECONDS.toSeconds(elapsedTime));
    } else if (elapsedTime < DateUtils.HOUR_IN_MILLIS) {
        formattedTimestamp = String.format("%dm", TimeUnit.MILLISECONDS.toMinutes(elapsedTime));
    } else if (elapsedTime < DateUtils.DAY_IN_MILLIS) {
        formattedTimestamp = String.format("%dh", TimeUnit.MILLISECONDS.toHours(elapsedTime));
    } else {
        formattedTimestamp = String.format("%dd", TimeUnit.MILLISECONDS.toDays(elapsedTime));
    }

    return formattedTimestamp;
}