Java Code Examples for android.text.format.DateUtils#getRelativeTimeSpanString()
The following examples show how to use
android.text.format.DateUtils#getRelativeTimeSpanString() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TimelineFragment.java From Yamba with Apache License 2.0 | 6 votes |
@Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { long timestamp; // Custom binding switch (view.getId()) { case R.id.list_item_text_created_at: timestamp = cursor.getLong(columnIndex); CharSequence relTime = DateUtils .getRelativeTimeSpanString(timestamp); ((TextView) view).setText(relTime); return true; case R.id.list_item_freshness: timestamp = cursor.getLong(columnIndex); ((FreshnessView) view).setTimestamp(timestamp); return true; default: return false; } }
Example 2
Source File: Post.java From Broadsheet.ie-Android with MIT License | 6 votes |
@SuppressLint("SimpleDateFormat") public String getRelativeTime() { if (relativeTime == null) { relativeTime = ""; SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date result = null; try { result = df.parse(this.date); relativeTime = (String) DateUtils.getRelativeTimeSpanString(result.getTime(), new Date().getTime(), DateUtils.MINUTE_IN_MILLIS); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return relativeTime; }
Example 3
Source File: RepliesListAdapter.java From mimi-reader with Apache License 2.0 | 6 votes |
private void setupReplies() { this.timeMap = new CharSequence[replies.size() + 1]; for (int i = 0; i < replies.size(); i++) { final ChanPost post = replies.get(i); final CharSequence dateString = DateUtils.getRelativeTimeSpanString( post.getTime() * 1000L, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE); if (post.getFilename() != null && !"".equals(post.getFilename())) { thumbUrlMap.put(post.getNo(), MimiUtil.https() + activity.getString(R.string.thumb_link) + activity.getString(R.string.thumb_path, boardName, post.getTim())); } timeMap[i] = dateString; } }
Example 4
Source File: AboutChromePreferences.java From 365browser with Apache License 2.0 | 6 votes |
/** * Build the application version to be shown. In particular, this ensures the debug build * versions are more useful. */ public static String getApplicationVersion(Context context, String version) { if (ChromeVersionInfo.isOfficialBuild()) { return version; } // For developer builds, show how recently the app was installed/updated. PackageInfo info; try { info = context.getPackageManager().getPackageInfo( context.getPackageName(), 0); } catch (NameNotFoundException e) { return version; } CharSequence updateTimeString = DateUtils.getRelativeTimeSpanString( info.lastUpdateTime, System.currentTimeMillis(), 0); return context.getString(R.string.version_with_update_time, version, updateTimeString); }
Example 5
Source File: UiUtils.java From tindroid with Apache License 2.0 | 6 votes |
@NonNull private static CharSequence relativeDateFormat(Context context, Date then) { if (then == null) { return context.getString(R.string.never); } long thenMillis = then.getTime(); if (thenMillis == 0) { return context.getString(R.string.never); } long nowMillis = System.currentTimeMillis(); if (nowMillis - thenMillis < DateUtils.MINUTE_IN_MILLIS) { return context.getString(R.string.just_now); } return DateUtils.getRelativeTimeSpanString(thenMillis, nowMillis, DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_ALL); }
Example 6
Source File: AboutChromePreferences.java From AndroidChromium with Apache License 2.0 | 6 votes |
/** * Build the application version to be shown. In particular, this ensures the debug build * versions are more useful. */ public static String getApplicationVersion(Context context, String version) { if (ChromeVersionInfo.isOfficialBuild()) { return version; } // For developer builds, show how recently the app was installed/updated. PackageInfo info; try { info = context.getPackageManager().getPackageInfo( context.getPackageName(), 0); } catch (NameNotFoundException e) { return version; } CharSequence updateTimeString = DateUtils.getRelativeTimeSpanString( info.lastUpdateTime, System.currentTimeMillis(), 0); return context.getString(R.string.version_with_update_time, version, updateTimeString); }
Example 7
Source File: SnippetArticleViewHolder.java From 365browser with Apache License 2.0 | 6 votes |
private static String getArticleAge(SnippetArticle article) { if (article.mPublishTimestampMilliseconds == 0) return ""; // DateUtils.getRelativeTimeSpanString(...) calls through to TimeZone.getDefault(). If this // has never been called before it loads the current time zone from disk. In most likelihood // this will have been called previously and the current time zone will have been cached, // but in some cases (eg instrumentation tests) it will cause a strict mode violation. StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); CharSequence relativeTimeSpan; try { long time = SystemClock.elapsedRealtime(); relativeTimeSpan = DateUtils.getRelativeTimeSpanString(article.mPublishTimestampMilliseconds, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS); RecordHistogram.recordTimesHistogram("Android.StrictMode.SnippetUIBuildTime", SystemClock.elapsedRealtime() - time, TimeUnit.MILLISECONDS); } finally { StrictMode.setThreadPolicy(oldPolicy); } // We add a dash before the elapsed time, e.g. " - 14 minutes ago". return String.format(ARTICLE_AGE_FORMAT_STRING, BidiFormatter.getInstance().unicodeWrap(relativeTimeSpan)); }
Example 8
Source File: Utils.java From android-discourse with Apache License 2.0 | 5 votes |
public static final CharSequence formatPostTime(long then) { CharSequence s = DateUtils.getRelativeTimeSpanString(then, System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS, DateUtils.FORMAT_ABBREV_ALL); return s; // if (isToday(then)) { // return getTodayPostTimeDisplay(then); // } else if (isInOneMonth(then)) { // return getInOneMonthPostTimeDisplay(then); // } else { // return getOutOneMonthPostTimeDisplay(then); // } }
Example 9
Source File: RelativeTimeTextView.java From Ninja with Apache License 2.0 | 5 votes |
private CharSequence getRelativeTimeDisplayString() { long now = System.currentTimeMillis(); long difference = now - mReferenceTime; return (difference >= 0 && difference<=DateUtils.MINUTE_IN_MILLIS) ? getResources().getString(R.string.android_ago_just_now): DateUtils.getRelativeTimeSpanString( mReferenceTime, now, DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE); }
Example 10
Source File: BlockedMessagesAdapter.java From NekoSMS with GNU General Public License v3.0 | 5 votes |
@Override public void onBindViewHolder(BlockedSmsItemHolder holder, Cursor cursor) { final SmsMessageData messageData = BlockedSmsLoader.get().getData(cursor, getColumns(), holder.mMessageData); holder.mMessageData = messageData; String sender = messageData.getSender(); long timeSent = messageData.getTimeSent(); String body = messageData.getBody(); CharSequence timeSentString = DateUtils.getRelativeTimeSpanString(mFragment.getContext(), timeSent); holder.mSenderTextView.setText(sender); holder.mTimeSentTextView.setText(timeSentString); holder.mBodyTextView.setText(body); if (messageData.isRead()) { holder.mSenderTextView.setTypeface(null, Typeface.NORMAL); holder.mTimeSentTextView.setTypeface(null, Typeface.NORMAL); holder.mBodyTextView.setTypeface(null, Typeface.NORMAL); } else { holder.mSenderTextView.setTypeface(null, Typeface.BOLD); holder.mTimeSentTextView.setTypeface(null, Typeface.BOLD); holder.mBodyTextView.setTypeface(null, Typeface.BOLD); } holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFragment.showMessageDetailsDialog(messageData); } }); }
Example 11
Source File: ParseDateFormat.java From mvvm-template with GNU General Public License v3.0 | 5 votes |
@NonNull public static CharSequence getTimeAgo(@Nullable String toParse) { try { Date parsedDate = getInstance().dateFormat.parse(toParse); long now = System.currentTimeMillis(); return DateUtils.getRelativeTimeSpanString(parsedDate.getTime(), now, DateUtils.SECOND_IN_MILLIS); } catch (Exception e) { e.printStackTrace(); } return "N/A"; }
Example 12
Source File: RelativeTimeTextView.java From Android_Skin_2.0 with Apache License 2.0 | 5 votes |
private synchronized void updateDisplay() { long now = System.currentTimeMillis(); long difference = now - mReferenceTime; CharSequence desc = null; if (difference >= 0 && difference <= DateUtils.MINUTE_IN_MILLIS && !TextUtils.isEmpty(mJustNow)) { desc = mJustNow; } else { desc = DateUtils.getRelativeTimeSpanString(mReferenceTime, now, DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE); } setText(desc); }
Example 13
Source File: BlobDescriptorListAdapter.java From aard2-android with GNU General Public License v3.0 | 5 votes |
@Override public View getView(int position, View convertView, ViewGroup parent) { BlobDescriptor item = list.get(position); CharSequence timestamp = DateUtils.getRelativeTimeSpanString(item.createdAt); View view; if (convertView != null) { view = convertView; } else { LayoutInflater inflater = (LayoutInflater) parent.getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.blob_descriptor_list_item, parent, false); } TextView titleView = (TextView) view .findViewById(R.id.blob_descriptor_key); titleView.setText(item.key); TextView sourceView = (TextView) view .findViewById(R.id.blob_descriptor_source); Slob slob = list.resolveOwner(item); sourceView.setText(slob == null ? "???" : slob.getTags().get("label")); TextView timestampView = (TextView) view .findViewById(R.id.blob_descriptor_timestamp); timestampView.setText(timestamp); CheckBox cb = (CheckBox) view .findViewById(R.id.blob_descriptor_checkbox); cb.setVisibility(isSelectionMode() ? View.VISIBLE : View.GONE); return view; }
Example 14
Source File: FormatterUtil.java From social-app-android with Apache License 2.0 | 5 votes |
public static CharSequence getRelativeTimeSpanString(Context context, long time) { long now = System.currentTimeMillis(); long range = Math.abs(now - time); if (range < NOW_TIME_RANGE) { return context.getString(R.string.now_time_range); } return DateUtils.getRelativeTimeSpanString(time, now, DateUtils.MINUTE_IN_MILLIS); }
Example 15
Source File: FileItem.java From rcloneExplorer with MIT License | 5 votes |
private String modTimeToHumanReadable(String modTime) { long now = System.currentTimeMillis(); long dateInMillis = modTimeToMilis(modTime); CharSequence humanReadable = DateUtils.getRelativeTimeSpanString(dateInMillis, now, DateUtils.MINUTE_IN_MILLIS); if (humanReadable.toString().startsWith("In") || humanReadable.toString().startsWith("0")) { humanReadable = "Now"; } return humanReadable.toString(); }
Example 16
Source File: Helper.java From FairEmail with GNU General Public License v3.0 | 5 votes |
static CharSequence getRelativeTimeSpanString(Context context, long millis) { long now = System.currentTimeMillis(); long span = Math.abs(now - millis); Time nowTime = new Time(); Time thenTime = new Time(); nowTime.set(now); thenTime.set(millis); if (span < DateUtils.DAY_IN_MILLIS && nowTime.weekDay == thenTime.weekDay) return getTimeInstance(context, SimpleDateFormat.SHORT).format(millis); else return DateUtils.getRelativeTimeSpanString(context, millis); }
Example 17
Source File: AttendanceActivity.java From bunk with MIT License | 4 votes |
private void processAndDisplayAttendance() { ArrayList<SubjectView> subjectViews = new ArrayList<>(); Boolean updated = false; for (Subject subject : this.newStudent.subjects.values()) { SubjectView subjectView = new SubjectView(); subjectView.avatar = subjectAvatar(subject.code); subjectView.name = subject.name; subjectView.attendance = String.format(Locale.US, "%.0f%%", Math.floor(subject.attendance())); subjectView.theory = String.format(Locale.US, subject.theoryTotal == 1 ? "%d/%d class" : "%d/%d classes", subject.theoryPresent, subject.theoryTotal); subjectView.lab = String.format(Locale.US, subject.labTotal == 1 ? "%d/%d class" : "%d/%d classes", subject.labPresent, subject.labTotal); subjectView.absent = String.format(Locale.US, subject.absent() == 1 ? "%d class" : "%d classes", subject.absent()); if (this.oldStudent.subjects.containsKey(subject.code)) { Subject oldSubject = this.oldStudent.subjects.get(subject.code); if (subject.theoryPresent != oldSubject.theoryPresent || subject.theoryTotal != oldSubject.theoryTotal || subject.labPresent != oldSubject.labPresent || subject.labTotal != oldSubject.labTotal) { updated = true; subjectView.oldTheory = String.format(Locale.US, oldSubject.theoryTotal == 1 ? "%d/%d class" : "%d/%d classes", oldSubject.theoryPresent, oldSubject.theoryTotal); subjectView.oldLab = String.format(Locale.US, oldSubject.labTotal == 1 ? "%d/%d class" : "%d/%d classes", oldSubject.labPresent, oldSubject.labTotal); subjectView.oldAbsent = String.format(Locale.US, oldSubject.absent() == 1 ? "%d class" : "%d classes", oldSubject.absent()); subjectView.updated = true; if (subject.attendance() >= oldSubject.attendance()) { subjectView.status = R.drawable.ic_status_up; } else { subjectView.status = R.drawable.ic_status_down; } } else { subject.lastUpdated = oldSubject.lastUpdated; } } if (subject.attendance() >= this.prefMinimumAttendance + 10.0) { subjectView.attendanceBadge = R.drawable.bg_badge_green; } else if (subject.attendance() >= this.prefMinimumAttendance) { subjectView.attendanceBadge = R.drawable.bg_badge_yellow; } else { subjectView.attendanceBadge = R.drawable.bg_badge_red; } subjectView.bunkStats = subject.bunkStats(this.prefMinimumAttendance, this.prefExtendedStats); if (subjectView.updated) { subjectView.lastUpdated = "just now"; } else { CharSequence timeSpan = DateUtils.getRelativeTimeSpanString(subject.lastUpdated, new Date().getTime(), 0); subjectView.lastUpdated = timeSpan.toString().toLowerCase(); } subjectViews.add(subjectView); } this.cache.setStudent(this.newStudent.username, this.newStudent); if (updated) { Toast.makeText(this.context, "Attendance updated", Toast.LENGTH_SHORT).show(); Vibrator vibrator = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(500); } findViewById(R.id.no_attendance).setVisibility(subjectViews.isEmpty() ? View.VISIBLE : View.GONE); findViewById(R.id.subjects).setVisibility(subjectViews.isEmpty() ? View.GONE : View.VISIBLE); this.subjectViews.clear(); this.subjectViews.addAll(subjectViews); this.subjectAdapter.notifyDataSetChanged(); }
Example 18
Source File: LocationService.java From trekarta with GNU General Public License v3.0 | 4 votes |
private Notification getNotification() { int titleId = R.string.notifTracking; int ntfId = R.mipmap.ic_stat_tracking; if (mGpsStatus != LocationService.GPS_OK) { titleId = R.string.notifLocationWaiting; ntfId = R.mipmap.ic_stat_waiting; } if (mGpsStatus == LocationService.GPS_OFF) { ntfId = R.mipmap.ic_stat_off; } if (mErrorTime > 0) { titleId = R.string.notifTrackingFailure; ntfId = R.mipmap.ic_stat_failure; } String timeTracked = (String) DateUtils.getRelativeTimeSpanString(getApplicationContext(), mTrackStarted); String distanceTracked = StringFormatter.distanceH(mDistanceTracked); StringBuilder sb = new StringBuilder(40); sb.append(getString(R.string.msgTracked, distanceTracked, timeTracked)); String message = sb.toString(); sb.insert(0, ". "); sb.insert(0, getString(R.string.msgTracking)); sb.append(". "); sb.append(getString(R.string.msgTrackingActions)); sb.append("."); String bigText = sb.toString(); Intent iLaunch = new Intent(Intent.ACTION_MAIN); iLaunch.addCategory(Intent.CATEGORY_LAUNCHER); iLaunch.setComponent(new ComponentName(getApplicationContext(), MainActivity.class)); iLaunch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); PendingIntent piResult = PendingIntent.getActivity(this, 0, iLaunch, PendingIntent.FLAG_CANCEL_CURRENT); Intent iStop = new Intent(DISABLE_TRACK, null, getApplicationContext(), LocationService.class); iStop.putExtra("self", true); PendingIntent piStop = PendingIntent.getService(this, 0, iStop, PendingIntent.FLAG_CANCEL_CURRENT); Icon stopIcon = Icon.createWithResource(this, R.drawable.ic_stop); Intent iPause = new Intent(PAUSE_TRACK, null, getApplicationContext(), LocationService.class); PendingIntent piPause = PendingIntent.getService(this, 0, iPause, PendingIntent.FLAG_CANCEL_CURRENT); Icon pauseIcon = Icon.createWithResource(this, R.drawable.ic_pause); Notification.Action actionStop = new Notification.Action.Builder(stopIcon, getString(R.string.actionStop), piStop).build(); Notification.Action actionPause = new Notification.Action.Builder(pauseIcon, getString(R.string.actionPause), piPause).build(); Notification.Builder builder = new Notification.Builder(this); if (Build.VERSION.SDK_INT > 25) builder.setChannelId("ongoing"); builder.setWhen(mErrorTime); builder.setSmallIcon(ntfId); builder.setContentIntent(piResult); builder.setContentTitle(getText(titleId)); builder.setStyle(new Notification.BigTextStyle().setBigContentTitle(getText(titleId)).bigText(bigText)); builder.addAction(actionPause); builder.addAction(actionStop); builder.setGroup("maptrek"); builder.setCategory(Notification.CATEGORY_SERVICE); builder.setPriority(Notification.PRIORITY_LOW); builder.setVisibility(Notification.VISIBILITY_PUBLIC); builder.setColor(getResources().getColor(R.color.colorAccent, getTheme())); if (mErrorTime > 0 && DEBUG_ERRORS) builder.setContentText(mErrorMsg); else builder.setContentText(message); builder.setOngoing(true); return builder.build(); }
Example 19
Source File: Utils.java From Hews with MIT License | 4 votes |
public static CharSequence formatTime(long timeStamp) { timeStamp = timeStamp * 1000; CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(timeStamp, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS); return timeAgo; }
Example 20
Source File: SnippetArticleViewHolder.java From AndroidChromium with Apache License 2.0 | 4 votes |
public void onBindViewHolder(SnippetArticle article) { super.onBindViewHolder(); // No longer listen for offline status changes to the old article. if (mArticle != null) mArticle.setOfflineStatusChangeRunnable(null); mArticle = article; updateLayout(); mHeadlineTextView.setText(mArticle.mTitle); // DateUtils.getRelativeTimeSpanString(...) calls through to TimeZone.getDefault(). If this // has never been called before it loads the current time zone from disk. In most likelihood // this will have been called previously and the current time zone will have been cached, // but in some cases (eg instrumentation tests) it will cause a strict mode violation. StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); try { long time = SystemClock.elapsedRealtime(); CharSequence relativeTimeSpan = DateUtils.getRelativeTimeSpanString( mArticle.mPublishTimestampMilliseconds, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS); RecordHistogram.recordTimesHistogram("Android.StrictMode.SnippetUIBuildTime", SystemClock.elapsedRealtime() - time, TimeUnit.MILLISECONDS); // We format the publisher here so that having a publisher name in an RTL language // doesn't mess up the formatting on an LTR device and vice versa. String publisherAttribution = String.format(PUBLISHER_FORMAT_STRING, BidiFormatter.getInstance().unicodeWrap(mArticle.mPublisher), relativeTimeSpan); mPublisherTextView.setText(publisherAttribution); } finally { StrictMode.setThreadPolicy(oldPolicy); } // The favicon of the publisher should match the TextView height. int widthSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); int heightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); mPublisherTextView.measure(widthSpec, heightSpec); mPublisherFaviconSizePx = mPublisherTextView.getMeasuredHeight(); mArticleSnippetTextView.setText(mArticle.mPreviewText); // If there's still a pending thumbnail fetch, cancel it. cancelImageFetch(); // If the article has a thumbnail already, reuse it. Otherwise start a fetch. // mThumbnailView's visibility is modified in updateLayout(). if (mThumbnailView.getVisibility() == View.VISIBLE) { if (mArticle.getThumbnailBitmap() != null) { mThumbnailView.setImageBitmap(mArticle.getThumbnailBitmap()); } else { mThumbnailView.setImageResource(R.drawable.ic_snippet_thumbnail_placeholder); mImageCallback = new FetchImageCallback(this, mArticle); mNewTabPageManager.getSuggestionsSource() .fetchSuggestionImage(mArticle, mImageCallback); } } // Set the favicon of the publisher. try { fetchFaviconFromLocalCache(new URI(mArticle.mUrl), true); } catch (URISyntaxException e) { setDefaultFaviconOnView(); } mOfflineBadge.setVisibility(View.GONE); if (SnippetsConfig.isOfflineBadgeEnabled()) { Runnable offlineChecker = new Runnable() { @Override public void run() { if (mArticle.getOfflinePageOfflineId() != null || mArticle.mIsDownloadedAsset) { mOfflineBadge.setVisibility(View.VISIBLE); } } }; mArticle.setOfflineStatusChangeRunnable(offlineChecker); offlineChecker.run(); } mRecyclerView.onSnippetBound(itemView); }