Example usage for android.text.format DateUtils HOUR_IN_MILLIS

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

Introduction

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

Prototype

long HOUR_IN_MILLIS

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

Click Source Link

Usage

From source file:Main.java

/**
 * Calculates how many hours are in given period. If one of the dates only partially covers the hour, it still counts as full hour.
 *
 * @param start Start of the period.//from w  w w .jav a 2s  . c  o  m
 * @param end   End of the period.
 * @return Number of days in given period. If {@code end < start}, returns -1.
 */
public static int getHourCountInPeriod(long start, long end) {
    if (end < start)
        return -1;

    return (int) Math.ceil((double) (end - start) / DateUtils.HOUR_IN_MILLIS);
}

From source file:Main.java

public static void appendGmtOffset(StringBuilder sb, final int gmtOffset) {
    sb.append("GMT");

    if (gmtOffset < 0) {
        sb.append('-');
    } else {/*from   w w  w  . j  av  a 2  s .com*/
        sb.append('+');
    }

    final int p = Math.abs(gmtOffset);
    sb.append(p / DateUtils.HOUR_IN_MILLIS); // Hour

    final int min = (p / (int) DateUtils.MINUTE_IN_MILLIS) % 60;
    if (min != 0) { // Show minutes if non-zero
        sb.append(':');
        if (min < 10) {
            sb.append('0');
        }
        sb.append(min);
    }
}

From source file:Main.java

/**
 * Get formatted time./*  w  ww.j a  v  a2s.  c o  m*/
 *
 * @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:com.calgen.udacity.lego.ui.Utils.java

/**
 * @param mCursor needed to fetch data/*ww  w.ja  v a 2s.  co  m*/
 * @param context needed to fetch string resources
 * @return modified string as [date] by [author]
 */
public static String getModifiedByline(Cursor mCursor, Context context) {
    return String.format(context.getString(R.string.by_line),
            DateUtils
                    .getRelativeTimeSpanString(mCursor.getLong(ArticleLoader.Query.PUBLISHED_DATE),
                            System.currentTimeMillis(), DateUtils.HOUR_IN_MILLIS, DateUtils.FORMAT_ABBREV_ALL)
                    .toString(),
            mCursor.getString(ArticleLoader.Query.AUTHOR));
}

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//w w  w.ja  va 2  s  .  c o  m
 *
 * @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:org.peterbaldwin.vlcremote.model.Preferences.java

/**
 * Returns {@code true} if {@link #setResumeOnIdle()} was called in the last
 * hour.//from   w ww. j  av  a  2s .  c  o  m
 */
public boolean isResumeOnIdleSet() {
    long start = mPreferences.getLong(PREFERENCE_RESUME_ON_IDLE, 0L);
    long end = System.currentTimeMillis();
    return start < end && (end - start) < DateUtils.HOUR_IN_MILLIS;
}

From source file:org.voidsink.anewjkuapp.mensa.JSONMenuLoader.java

private String getData(Context context) {
    String result = null;//  w w w.ja  v  a  2s .  c om
    String cacheDateKey = PREF_DATE_PREFIX + getCacheKey();
    String cacheDataKey = PREF_DATA_PREFIX + getCacheKey();

    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    if (sp.getLong(cacheDateKey, 0) > (System.currentTimeMillis() - 6 * DateUtils.HOUR_IN_MILLIS)) {
        result = sp.getString(cacheDataKey, null);
    }

    if (result == null) {
        try {
            URL url = new URL(getUrl());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(15000);

            Writer writer = new StringWriter();

            char[] buffer = new char[1024];
            Reader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
            result = writer.toString();

            conn.disconnect();

            Editor editor = sp.edit();
            editor.putString(cacheDataKey, result);
            editor.putLong(cacheDateKey, System.currentTimeMillis());
            editor.apply();
        } catch (Exception e) {
            Analytics.sendException(context, e, false);
            result = sp.getString(cacheDataKey, null);
        }
    }

    return result;
}

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

public String getFormattedTimestamp() {
    String formattedTimestamp;/*from  ww  w.j  a  v a 2  s . co  m*/
    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;
}

From source file:com.abourazanis.muzei.wallbase.WallhavenSettings.java

private void setupIntervalSpinner() {
    mIntervalList.clear();//from   w w w  .  j  a  v a2 s.c om
    mIntervalList.add(new Interval(R.string.threeHours, 3 * DateUtils.HOUR_IN_MILLIS));
    mIntervalList.add(new Interval(R.string.sixHours, 6 * DateUtils.HOUR_IN_MILLIS));
    mIntervalList.add(new Interval(R.string.nineHours, 9 * DateUtils.HOUR_IN_MILLIS));
    mIntervalList.add(new Interval(R.string.twelveHours, 12 * DateUtils.HOUR_IN_MILLIS));
    mIntervalList.add(new Interval(R.string.day, DateUtils.DAY_IN_MILLIS));

    mUpdateIntervalSpinner
            .setAdapter(new ArrayAdapter<Interval>(this, android.R.layout.simple_list_item_1, mIntervalList));
    mUpdateIntervalSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            PreferenceHelper.setConfigFreq(view.getContext(),
                    (int) mIntervalList.get(position).getTimeMillis());
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });

    int preference = PreferenceHelper.getConfigFreq(this);

    for (int i = 0; i < mIntervalList.size(); i++)
        if (preference == mIntervalList.get(i).getTimeMillis()) {
            mUpdateIntervalSpinner.setSelection(i, true);
        }
}

From source file:com.example.xyzreader.ui.articlelist.ArticleListAdapter.java

@Override
public void onBindViewHolder(final ViewHolder viewHolder, Cursor cursor) {

    // set up the animation per the xml files
    int position = cursor.getPosition();
    Animation animation = AnimationUtils.loadAnimation(mContext,
            (position > mLastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
    viewHolder.itemView.startAnimation(animation);
    mLastPosition = position;/*from ww  w. j  a v a  2  s  . c  o  m*/

    //show the thumb image (with progress spinner) or the "not found" image
    viewHolder.mArticleListImageProgressBar.setVisibility(View.VISIBLE);
    Picasso.with(mContext).load(cursor.getString(ArticleLoader.Query.THUMB_URL))
            .into(viewHolder.mArticleListImageView, new Callback() {
                @Override
                public void onSuccess() {
                    viewHolder.mArticleListImageProgressBar.setVisibility(View.GONE);
                }

                @Override
                public void onError() {
                    viewHolder.mArticleListImageView.setImageResource(R.mipmap.ic_launcher);
                }
            });

    // show the title and byline
    viewHolder.mArticleListItemTitle.setText(cursor.getString(ArticleLoader.Query.TITLE));
    String byLine = DateUtils
            .getRelativeTimeSpanString(cursor.getLong(ArticleLoader.Query.PUBLISHED_DATE),
                    System.currentTimeMillis(), DateUtils.HOUR_IN_MILLIS, DateUtils.FORMAT_ABBREV_ALL)
            .toString() + " by " + cursor.getString(ArticleLoader.Query.AUTHOR);
    viewHolder.mArticleListItemByLine.setText(byLine);
}