android.text.format.DateUtils Java Examples

The following examples show how to use android.text.format.DateUtils. 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: BindingAdapters.java    From lttrs-android with Apache License 2.0 6 votes vote down vote up
@BindingAdapter("date")
public static void setInteger(TextView textView, Date receivedAt) {
    if (receivedAt == null || receivedAt.getTime() <= 0) {
        textView.setVisibility(View.GONE);
    } else {
        Context context = textView.getContext();
        Calendar specifiedDate = Calendar.getInstance();
        specifiedDate.setTime(receivedAt);
        Calendar today = Calendar.getInstance();
        textView.setVisibility(View.VISIBLE);

        long diff = today.getTimeInMillis() - specifiedDate.getTimeInMillis();

        if (sameDay(today, specifiedDate) || diff < SIX_HOURS) {
            textView.setText(DateUtils.formatDateTime(context, receivedAt.getTime(), DateUtils.FORMAT_SHOW_TIME));
        } else if (sameYear(today, specifiedDate) || diff < THREE_MONTH) {
            textView.setText(DateUtils.formatDateTime(context, receivedAt.getTime(), DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_YEAR | DateUtils.FORMAT_ABBREV_ALL));
        } else {
            textView.setText(DateUtils.formatDateTime(context, receivedAt.getTime(), DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_MONTH_DAY | DateUtils.FORMAT_ABBREV_ALL));
        }
    }
}
 
Example #2
Source File: ProviderSchematic.java    From cathode with Apache License 2.0 6 votes vote down vote up
public static String getAiredQuery() {
  final long firstAiredOffset = FirstAiredOffsetPreference.getInstance().getOffsetMillis();
  final long currentTime = System.currentTimeMillis();
  return "(SELECT COUNT(*) FROM "
      + Tables.EPISODES
      + " WHERE "
      + Tables.EPISODES
      + "."
      + EpisodeColumns.SHOW_ID
      + "="
      + Tables.SHOWS
      + "."
      + ShowColumns.ID
      + " AND "
      + Tables.EPISODES
      + "."
      + EpisodeColumns.FIRST_AIRED
      + "<="
      + (currentTime - firstAiredOffset + DateUtils.DAY_IN_MILLIS)
      + " AND "
      + Tables.EPISODES
      + "."
      + EpisodeColumns.SEASON
      + ">0"
      + ")";
}
 
Example #3
Source File: SpotRules.java    From android with MIT License 6 votes vote down vote up
/**
 * For a 24/7 interval, return remaining parking time.
 * For NONE and PAID, duration is a full week.
 * For time-based restrictions, duration is TimeMax.
 *
 * @param intervals The agenda's intervals, sorted and starting today
 * @return Millis remaining following the 24/7 interval rule
 */
private static long getFullWeekRemainingTime(RestrIntervalsList intervals) {
    final RestrInterval interval = intervals.get(0);

    switch (interval.getType()) {
        case Const.ParkingRestrType.ALL_TIMES:
            // Special case when viewing a NoParking spot.
            // UX doesn't normally display SpotInfo for such spots.
            return 0;
        case Const.ParkingRestrType.TIME_MAX:
        case Const.ParkingRestrType.TIME_MAX_PAID:
            return interval.getTimeMaxMillis();
        case Const.ParkingRestrType.PAID:
        case Const.ParkingRestrType.NONE:
        default:
            return DateUtils.WEEK_IN_MILLIS;
    }
}
 
Example #4
Source File: MessageAdapter.java    From BLEMeshChat with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void onBindViewHolder(ViewHolder holder, Cursor cursor) {
    holder.container.setTag(R.id.view_tag_msg_id, cursor.getInt(cursor.getColumnIndex(MessageTable.id)));

    if (holder.peer == null) // TODO : Should do this lookup on a background thread
        holder.peer = mDataStore.getPeerById(cursor.getInt(cursor.getColumnIndex(MessageTable.peerId)));

    if (holder.peer != null) {
        holder.container.setTag(R.id.view_tag_peer_id, holder.peer.getId());
        holder.senderView.setText(holder.peer.getAlias());
        holder.identicon.show(new String(holder.peer.getPublicKey()));
    } else {
        holder.senderView.setText("?");
        holder.identicon.show(UUID.randomUUID());
    }
    holder.messageView.setText(cursor.getString(cursor.getColumnIndex(MessageTable.body)));
    try {
        holder.authoredView.setText(DateUtils.getRelativeTimeSpanString(
                DataUtil.storedDateFormatter.parse(cursor.getString(cursor.getColumnIndex(MessageTable.authoredDate))).getTime()));
    } catch (ParseException e) {
        holder.authoredView.setText("");
        e.printStackTrace();
    }
}
 
Example #5
Source File: RadialPickerLayout.java    From cathode with Apache License 2.0 6 votes vote down vote up
/**
 * Announce the currently-selected time when launched.
 */
@Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
  if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
    // Clear the event's current text so that only the current time will be spoken.
    event.getText().clear();
    Time time = new Time();
    time.hour = getHours();
    time.minute = getMinutes();
    long millis = time.normalize(true);
    int flags = DateUtils.FORMAT_SHOW_TIME;
    if (mIs24HourMode) {
      flags |= DateUtils.FORMAT_24HOUR;
    }
    String timeString = DateUtils.formatDateTime(getContext(), millis, flags);
    event.getText().add(timeString);
    return true;
  }
  return super.dispatchPopulateAccessibilityEvent(event);
}
 
Example #6
Source File: ConnectivityController.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Test to see if running the given job on the given network is insane.
 * <p>
 * For example, if a job is trying to send 10MB over a 128Kbps EDGE
 * connection, it would take 10.4 minutes, and has no chance of succeeding
 * before the job times out, so we'd be insane to try running it.
 */
@SuppressWarnings("unused")
private static boolean isInsane(JobStatus jobStatus, Network network,
        NetworkCapabilities capabilities, Constants constants) {
    final long estimatedBytes = jobStatus.getEstimatedNetworkBytes();
    if (estimatedBytes == JobInfo.NETWORK_BYTES_UNKNOWN) {
        // We don't know how large the job is; cross our fingers!
        return false;
    }

    // We don't ask developers to differentiate between upstream/downstream
    // in their size estimates, so test against the slowest link direction.
    final long slowest = NetworkCapabilities.minBandwidth(
            capabilities.getLinkDownstreamBandwidthKbps(),
            capabilities.getLinkUpstreamBandwidthKbps());
    if (slowest == LINK_BANDWIDTH_UNSPECIFIED) {
        // We don't know what the network is like; cross our fingers!
        return false;
    }

    final long estimatedMillis = ((estimatedBytes * DateUtils.SECOND_IN_MILLIS)
            / (slowest * TrafficStats.KB_IN_BYTES / 8));
    if (estimatedMillis > JobServiceContext.EXECUTING_TIMESLICE_MILLIS) {
        // If we'd never finish before the timeout, we'd be insane!
        Slog.w(TAG, "Estimated " + estimatedBytes + " bytes over " + slowest
                + " kbps network would take " + estimatedMillis + "ms; that's insane!");
        return true;
    } else {
        return false;
    }
}
 
Example #7
Source File: JobService.java    From firebase-jobdispatcher-android with Apache License 2.0 6 votes vote down vote up
/**
 * Package-private alias for {@link #dump(FileDescriptor, PrintWriter, String[])}.
 *
 * <p>The {@link #dump(FileDescriptor, PrintWriter, String[])} method is protected. This
 * implementation method is marked package-private to facilitate testing.
 */
@VisibleForTesting
final void dumpImpl(PrintWriter writer) {
  synchronized (runningJobs) {
    if (runningJobs.isEmpty()) {
      writer.println("No running jobs");
      return;
    }

    long now = SystemClock.elapsedRealtime();

    writer.println("Running jobs:");
    for (int i = 0; i < runningJobs.size(); i++) {
      JobCallback callback = runningJobs.get(runningJobs.keyAt(i));

      // Add sanitized quotes around the tag to make this easier to parse for robots
      String name = JSONObject.quote(callback.job.getTag());
      // Produces strings like "02:30"
      String duration =
          DateUtils.formatElapsedTime(MILLISECONDS.toSeconds(now - callback.startedAtElapsed));

      writer.println("    * " + name + " has been running for " + duration);
    }
  }
}
 
Example #8
Source File: AlgoliaPopularClient.java    From materialistic with Apache License 2.0 6 votes vote down vote up
private long toTimestamp(@Range String filter) {
    long timestamp = System.currentTimeMillis();
    switch (filter) {
        case LAST_24H:
        default:
            timestamp -= DateUtils.DAY_IN_MILLIS;
            break;
        case PAST_WEEK:
            timestamp -= DateUtils.WEEK_IN_MILLIS;
            break;
        case PAST_MONTH:
            timestamp -= DateUtils.WEEK_IN_MILLIS * 4;
            break;
        case PAST_YEAR:
            timestamp -= DateUtils.YEAR_IN_MILLIS;
            break;
    }
    return timestamp;
}
 
Example #9
Source File: FacebookTimeSpentData.java    From Abelana-Android with Apache License 2.0 6 votes vote down vote up
private void logAppDeactivatedEvent(AppEventsLogger logger,
                                    long interruptionDurationMillis) {
    // Log the old session information and clear the data
    Bundle eventParams = new Bundle();
    eventParams.putInt(
            AppEventsConstants.EVENT_NAME_SESSION_INTERRUPTIONS,
            interruptionCount);
    eventParams.putInt(
            AppEventsConstants.EVENT_NAME_TIME_BETWEEN_SESSIONS,
            getQuantaIndex(interruptionDurationMillis));
    eventParams.putString(
            AppEventsConstants.EVENT_PARAM_SOURCE_APPLICATION,
            firstOpenSourceApplication);
    logger.logEvent(
            AppEventsConstants.EVENT_NAME_DEACTIVATED_APP,
            (millisecondsSpentInSession/DateUtils.SECOND_IN_MILLIS),
            eventParams);
    resetSession();
}
 
Example #10
Source File: Utils.java    From fdroidclient with GNU General Public License v3.0 6 votes vote down vote up
public static String formatLastUpdated(@NonNull Resources res, @NonNull Date date) {
    long msDiff = Calendar.getInstance().getTimeInMillis() - date.getTime();
    long days = msDiff / DateUtils.DAY_IN_MILLIS;
    long weeks = msDiff / (DateUtils.DAY_IN_MILLIS * 7);
    long months = msDiff / (DateUtils.DAY_IN_MILLIS * 30);
    long years = msDiff / (DateUtils.DAY_IN_MILLIS * 365);

    if (days < 1) {
        return res.getString(R.string.details_last_updated_today);
    } else if (weeks < 1) {
        return res.getQuantityString(R.plurals.details_last_update_days, (int) days, days);
    } else if (months < 1) {
        return res.getQuantityString(R.plurals.details_last_update_weeks, (int) weeks, weeks);
    } else if (years < 1) {
        return res.getQuantityString(R.plurals.details_last_update_months, (int) months, months);
    } else {
        return res.getQuantityString(R.plurals.details_last_update_years, (int) years, years);
    }
}
 
Example #11
Source File: ClientSettingsFragment.java    From snapdroid with GNU General Public License v3.0 6 votes vote down vote up
public void update() {
    if (client == null)
        return;
    prefName.setSummary(client.getConfig().getName());
    prefName.setText(client.getConfig().getName());
    prefMac.setSummary(client.getHost().getMac());
    prefId.setSummary(client.getId());
    prefIp.setSummary(client.getHost().getIp());
    prefHost.setSummary(client.getHost().getName());
    prefOS.setSummary(client.getHost().getOs() + "@" + client.getHost().getArch());
    prefVersion.setSummary(client.getSnapclient().getVersion());
    String lastSeen = getText(R.string.online).toString();
    if (!client.isConnected()) {
        long lastSeenTs = Math.min(client.getLastSeen().getSec() * 1000, System.currentTimeMillis());
        lastSeen = DateUtils.getRelativeTimeSpanString(lastSeenTs, System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS).toString();
    }
    prefLastSeen.setSummary(lastSeen);
    prefLatency.setSummary(client.getConfig().getLatency() + "ms");
    prefLatency.setText(client.getConfig().getLatency() + "");
}
 
Example #12
Source File: DatePickerDialog.java    From MaterialDateTimePicker with Apache License 2.0 5 votes vote down vote up
private void updateDisplay(boolean announce) {
    mYearView.setText(YEAR_FORMAT.format(mCalendar.getTime()));

    if (mVersion == Version.VERSION_1) {
        if (mDatePickerHeaderView != null) {
            if (mTitle != null)
                mDatePickerHeaderView.setText(mTitle);
            else {
                mDatePickerHeaderView.setText(mCalendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG,
                        mLocale));
            }
        }
        mSelectedMonthTextView.setText(MONTH_FORMAT.format(mCalendar.getTime()));
        mSelectedDayTextView.setText(DAY_FORMAT.format(mCalendar.getTime()));
    }

    if (mVersion == Version.VERSION_2) {
        mSelectedDayTextView.setText(VERSION_2_FORMAT.format(mCalendar.getTime()));
        if (mTitle != null)
            mDatePickerHeaderView.setText(mTitle.toUpperCase(mLocale));
        else
            mDatePickerHeaderView.setVisibility(View.GONE);
    }

    // Accessibility.
    long millis = mCalendar.getTimeInMillis();
    mAnimator.setDateMillis(millis);
    int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_YEAR;
    String monthAndDayText = DateUtils.formatDateTime(getActivity(), millis, flags);
    mMonthAndDayView.setContentDescription(monthAndDayText);

    if (announce) {
        flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR;
        String fullDateText = DateUtils.formatDateTime(getActivity(), millis, flags);
        Utils.tryAccessibilityAnnounce(mAnimator, fullDateText);
    }
}
 
Example #13
Source File: Utils.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
public static String formatDateRange(Context context, long start, long end) {
	final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_MONTH;

	synchronized (sBuilder) {
		sBuilder.setLength(0);
		return DateUtils.formatDateRange(context, sFormatter, start, end,
				flags, null).toString();
	}
}
 
Example #14
Source File: Utils.java    From react-native-date-picker with MIT License 5 votes vote down vote up
public static Calendar getTruncatedCalendarOrNull(Calendar cal) {
    try {
        return org.apache.commons.lang3.time.DateUtils.truncate(cal, Calendar.MINUTE);
    } catch (Exception e){
        return null;
    }
}
 
Example #15
Source File: LastSeenTimeUtil.java    From iGap-Android with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * if last seen bigger than 10 minutes return local time otherwise
 * return minutes from latest user seen
 *
 * @param lastSeen time in second state(not millis)
 * @param update   if set true time updating after each Config.LAST_SEEN_DELAY_CHECKING time and send callback to onLastSeenUpdateTiming
 */
public static String computeTime(long userId, long lastSeen, boolean update, boolean ltr) {
    if (timeOut(lastSeen * DateUtils.SECOND_IN_MILLIS)) {
        return computeDays(lastSeen, ltr);
    } else {
        if (update) {
            hashMapLastSeen.put(userId, lastSeen);
            updateLastSeenTime();
        }
        return getMinute(lastSeen);
    }
}
 
Example #16
Source File: LayoutFaceService.java    From io18watchface with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Stops the {@link #updateTimeHandler} timer, then retsarts if it should be running.
 */
private void updateTimer() {
    updateTimeHandler.removeMessages(MSG_UPDATE_TIME);
    
    if (isVisible() && !isInAmbientMode()) {
        final long delayMs = DateUtils.SECOND_IN_MILLIS -
                (System.currentTimeMillis() % DateUtils.SECOND_IN_MILLIS);
        updateTimeHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIME, delayMs);
    }
}
 
Example #17
Source File: FormatterUtil.java    From social-app-android with Apache License 2.0 5 votes vote down vote up
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 #18
Source File: RelativeTimeTextView.java    From WaniKani-for-Android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void run() {
    long difference = Math.abs(System.currentTimeMillis() - mRefTime);
    long interval = DateUtils.MINUTE_IN_MILLIS;
    if (difference > DateUtils.WEEK_IN_MILLIS) {
        interval = DateUtils.WEEK_IN_MILLIS;
    } else if (difference > DateUtils.DAY_IN_MILLIS) {
        interval = DateUtils.DAY_IN_MILLIS;
    } else if (difference > DateUtils.HOUR_IN_MILLIS) {
        interval = DateUtils.HOUR_IN_MILLIS;
    }
    updateTextDisplay();
    mHandler.postDelayed(this, interval);

}
 
Example #19
Source File: DateSpinner.java    From ReminderDatePicker with Apache License 2.0 5 votes vote down vote up
private String formatSecondaryDate(@NonNull Calendar date) {
    if(secondaryDateFormat == null)
        return DateUtils.formatDateTime(getContext(), date.getTimeInMillis(),
                DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NUMERIC_DATE);
    else
        return secondaryDateFormat.format(date.getTime());
}
 
Example #20
Source File: RouteUtilTest.java    From msdkui-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testTime() {
    Spannable spannable = RouteUtil.getTimeToArrive(getApplicationContext(),
            new MockUtils.MockRouteBuilder().getRoute(), false);
    assertThat(spannable.toString(),
            equalTo(TimeFormatterUtil.format(getApplicationContext(), 1000 * DateUtils.SECOND_IN_MILLIS)));
}
 
Example #21
Source File: FilesAdapter.java    From mua with MIT License 5 votes vote down vote up
@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
    final FileEntity entity = dataSet.get(position);
    String fileName = entity.getName();
    holder.fileName.setText(fileName);

    String content = FileUtils.readContentFromFile(new File(entity.getAbsolutePath()), false);
    if (content.length() == 0) {
        holder.fileContent.setVisibility(View.GONE);
    } else {
        content = content.length() > 500 ? content.substring(0, 500) : content;
        holder.fileContent.setText(content);
    }

    holder.fileDate.setText(DateUtils.getRelativeTimeSpanString(entity.getLastModified(),
            System.currentTimeMillis(), DateUtils.FORMAT_ABBREV_ALL));

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Fragment fragment = new EditorFragment();

            Bundle args = new Bundle();
            args.putBoolean(Constants.BUNDLE_KEY_SAVED, true);
            args.putBoolean(Constants.BUNDLE_KEY_FROM_FILE, true);
            args.putString(Constants.BUNDLE_KEY_FILE_NAME,
                    FileUtils.stripExtension(entity.getName()));
            args.putString(Constants.BUNDLE_KEY_FILE_PATH, entity.getAbsolutePath());

            fragment.setArguments(args);
            context.getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_container, fragment)
                    .addToBackStack(null)
                    .commit();
        }
    });
}
 
Example #22
Source File: CommentsAdapter.java    From auth with MIT License 5 votes vote down vote up
@Override
public void onBindViewHolder(CommentViewHolder holder, int position) {
    Comment comment = comments.get(position);

    holder.text.setText(comment.body);

    double created_utc = comment.created_utc;
    String dateTime =
            DateUtils.formatDateTime(holder.itemView.getContext(), (long) created_utc, 0);
    holder.date.setText(dateTime);
}
 
Example #23
Source File: GcmFragment.java    From android_packages_apps_GmsCore with Apache License 2.0 5 votes vote down vote up
private void updateViewDetails() {
    if (database.getRegistrationsByApp(app.packageName).isEmpty()) {
        setSummary(R.string.gcm_not_registered);
    } else if (app.lastMessageTimestamp > 0) {
        setSummary(getContext().getString(R.string.gcm_last_message_at, DateUtils.getRelativeDateTimeString(getContext(), app.lastMessageTimestamp, MINUTE_IN_MILLIS, WEEK_IN_MILLIS, FORMAT_SHOW_TIME)));
    } else {
        setSummary(R.string.gcm_no_message_yet);
    }
    database.close();
}
 
Example #24
Source File: RelativeTimeTextView.java    From WaniKani-for-Android with GNU General Public License v3.0 5 votes vote down vote up
private CharSequence getRelativeTimeDisplayString() {
    long now = System.currentTimeMillis();
    long difference = now - mReferenceTime;
    return (difference >= 0 && difference <= DateUtils.MINUTE_IN_MILLIS) ?
            getResources().getString(R.string.just_now) :
            DateUtils.getRelativeTimeSpanString(
                    mReferenceTime,
                    now,
                    DateUtils.MINUTE_IN_MILLIS,
                    DateUtils.FORMAT_ABBREV_RELATIVE);
}
 
Example #25
Source File: InputPanel.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@MainThread
public void display() {
  this.startTime = System.currentTimeMillis();
  this.recordTimeView.setText(DateUtils.formatElapsedTime(0));
  ViewUtil.fadeIn(this.recordTimeView, FADE_TIME);
  Util.runOnMainDelayed(this, TimeUnit.SECONDS.toMillis(1));
  microphone.setVisibility(View.VISIBLE);
  microphone.startAnimation(pulseAnimation());
}
 
Example #26
Source File: MusicInfoActivity.java    From YCAudioPlayer with Apache License 2.0 5 votes vote down vote up
private String formatTime(String pattern, long milli) {
    int m = (int) (milli / DateUtils.MINUTE_IN_MILLIS);
    int s = (int) ((milli / DateUtils.SECOND_IN_MILLIS) % 60);
    String mm = String.format(Locale.getDefault(), "%02d", m);
    String ss = String.format(Locale.getDefault(), "%02d", s);
    return pattern.replace("mm", mm).replace("ss", ss);
}
 
Example #27
Source File: SessionMonitorTest.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testMonitorStateStartVerification_pastTimeThreshold() {
    final long startTime = TEST_TIME_1200_UTC;
    final long now = startTime + (8 * DateUtils.HOUR_IN_MILLIS);

    monitorState.lastVerification = startTime;
    monitorState.verifying = false;
    assertTrue(monitorState.beginVerification(now));
}
 
Example #28
Source File: ThreadListAdapter.java    From mimi-reader with Apache License 2.0 5 votes vote down vote up
private void setupThread() {
        this.timeMap = new CharSequence[items.size()];
        this.colorList = new int[items.size()];
//        this.userPostList = ThreadRegistry.getInstance().getUserPosts(boardName, threadId);

        final Context context = MimiApplication.getInstance().getApplicationContext();

        for (int i = 0; i < items.size(); i++) {
            final ChanPost post = items.get(i);
            final CharSequence dateString = DateUtils.getRelativeTimeSpanString(
                    post.getTime() * 1000L,
                    System.currentTimeMillis(),
                    DateUtils.MINUTE_IN_MILLIS,
                    DateUtils.FORMAT_ABBREV_RELATIVE);

            if (post.getFilename() != null && !post.getFilename().equals("")) {
                thumbUrlMap.put(post.getNo(), MimiUtil.https() + context.getString(R.string.thumb_link) + context.getString(R.string.thumb_path, boardName, post.getTim()));
                fullImageUrlMap.put(post.getNo(), MimiUtil.https() + context.getString(R.string.image_link) + context.getString(R.string.full_image_path, boardName, post.getTim(), post.getExt()));
            }

            repliesText.add(context.getResources().getQuantityString(R.plurals.replies_plural, post.getRepliesFrom().size(), post.getRepliesFrom().size()));
            imagesText.add(context.getResources().getQuantityString(R.plurals.image_plural, post.getImages(), post.getImages()));

            timeMap[i] = dateString;

            if (!TextUtils.isEmpty(post.getId())) {
                colorList[i] = ChanUtil.calculateColorBase(post.getId());
            }

            if (post.getFsize() > 0) {
                post.setHumanReadableFileSize(MimiUtil.humanReadableByteCount(post.getFsize(), true) + " " + post.getExt().substring(1).toUpperCase());
            }
        }

    }
 
Example #29
Source File: Util.java    From android-testdpc with Apache License 2.0 5 votes vote down vote up
/**
 * Format a friendly datetime for the current locale according to device policy documentation.
 * If the timestamp doesn't represent a real date, it will be interpreted as {@code null}.
 *
 * @return A {@link CharSequence} such as "12:35 PM today" or "June 15, 2033", or {@code null}
 * in the case that {@param timestampMs} equals zero.
 */
public static CharSequence formatTimestamp(long timestampMs) {
    if (timestampMs == 0) {
        // DevicePolicyManager documentation describes this timestamp as having no effect,
        // so show nothing for this case as the policy has not been set.
        return null;
    }

    return DateUtils.formatSameDayTime(timestampMs, System.currentTimeMillis(),
            DateUtils.FORMAT_SHOW_WEEKDAY, DateUtils.FORMAT_SHOW_TIME);
}
 
Example #30
Source File: RelativeTimeTextView.java    From Cracker with Apache License 2.0 5 votes vote down vote up
private CharSequence getRelativeTimeDisplayString() {
    long now = System.currentTimeMillis();
    long difference = now - mReferenceTime; 
    return (difference >= 0 &&  difference<=DateUtils.MINUTE_IN_MILLIS) ? 
            getResources().getString(R.string.just_now): 
            DateUtils.getRelativeTimeSpanString(
                mReferenceTime,
                now,
                DateUtils.MINUTE_IN_MILLIS,
                DateUtils.FORMAT_ABBREV_RELATIVE);
}