Java Code Examples for android.text.format.DateUtils

The following examples show how to use android.text.format.DateUtils. These examples are extracted from open source projects. 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 Project: BLEMeshChat   Source File: MessageAdapter.java    License: 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 2
Source Project: android_9.0.0_r45   Source File: ConnectivityController.java    License: 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 3
Source Project: cathode   Source File: RadialPickerLayout.java    License: 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 4
Source Project: Abelana-Android   Source File: FacebookTimeSpentData.java    License: 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 5
Source Project: lttrs-android   Source File: BindingAdapters.java    License: 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 6
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 7
Source Project: fdroidclient   Source File: Utils.java    License: 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 8
Source Project: materialistic   Source File: AlgoliaPopularClient.java    License: 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 Project: firebase-jobdispatcher-android   Source File: JobService.java    License: 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 10
Source Project: cathode   Source File: ProviderSchematic.java    License: 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 11
Source Project: android   Source File: SpotRules.java    License: 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 12
Source Project: mollyim-android   Source File: InputPanel.java    License: 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 13
Source Project: DateTimePicker   Source File: DatePickerSpinnerDelegate.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
    final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR;
    String selectedDateUtterance = DateUtils.formatDateTime(mContext,
            mCurrentDate.getTimeInMillis(), flags);
    event.getText().add(selectedDateUtterance);
}
 
Example 14
Source Project: edx-app-android   Source File: DiscussionTextUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static CharSequence getRelativeTimeSpanString(@NonNull Context context, long nowMs,
                                                     long timeMs, int flags) {
    if (nowMs - timeMs < DateUtils.SECOND_IN_MILLIS) {
        return context.getString(R.string.just_now);
    } else {
        return DateUtils.getRelativeTimeSpanString(timeMs, nowMs,
                DateUtils.SECOND_IN_MILLIS, flags);
    }
}
 
Example 15
Source Project: BottomSheetPickers   Source File: DateTimeFormatUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return {@code true} if the AM or PM label is written before the time
 *         in the user's locale.
 */
static boolean isAmPmWrittenBeforeTime(@NonNull Context context) {
    if (Build.VERSION.SDK_INT >= 18) {
        final String dateTimePattern = DateFormat.getBestDateTimePattern(
                getPrimaryLocale(context), "hm");
        return dateTimePattern.startsWith("a");
    } else {
        // Format a dummy time string in 12-hour time, then check if the string
        // starts with a non-digit character. This should be the AM/PM label.
        final String formatted12HourTime = DateUtils.formatDateTime(context,
                System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR);
        return !Character.isDigit(formatted12HourTime.charAt(0));
    }
}
 
Example 16
Source Project: NumberPadTimePicker   Source File: DateTimeFormatUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return The time separator used in the user's locale.
 */
static String getTimeSeparator(@NonNull Context context, boolean is24Hour) {
    // The time separator is defined in the Unicode CLDR and cannot be supposed to be ":".
    // See http://unicode.org/cldr/trac/browser/trunk/common/main.
    if (Build.VERSION.SDK_INT >= 18) {
        // We pass the correct "skeleton" depending on 12 or 24 hours view and then extract the
        // separator, which is the character just after the hour marker in the returned pattern.
        final String bestDateTimePattern = DateFormat.getBestDateTimePattern(
                getPrimaryLocale(context), (is24Hour) ? "Hm" : "hm");
        final String separatorText;
        // See http://www.unicode.org/reports/tr35/tr35-dates.html for hour formats
        final char[] hourFormats = {'H', 'h', 'K', 'k'};
        int hIndex = lastIndexOfAny(bestDateTimePattern, hourFormats);
        if (hIndex == -1) {
            // Default case
            separatorText = ":";
        } else {
            separatorText = Character.toString(bestDateTimePattern.charAt(hIndex + 1));
        }
        return separatorText;
    } else {
        // Format a dummy time string in 24-hour time, then iterate through the string until
        // we find a non-digit character.
        final String formatted24HourTime = DateUtils.formatDateTime(context,
                System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_24HOUR);
        for (int i = 0; i < formatted24HourTime.length(); i++) {
            final char c = formatted24HourTime.charAt(i);
            if (!Character.isDigit(c)) {
                return Character.toString(c);
            }
        }
        return "";
    }
}
 
Example 17
@Override
public void run() {
    long currentTime = System.currentTimeMillis();
    long seconds = (currentTime - startTime) / 1000;
    String formattedDuration = DateUtils.formatElapsedTime(seconds);
    textViewDuration.setText(formattedDuration);
    if (isRecording()) {
        handler.postDelayed(this, 1000L);
    }
}
 
Example 18
@NonNull public static CharSequence getTimeAgo(@Nullable Date parsedDate) {
    if (parsedDate != null) {
        long now = System.currentTimeMillis();
        return DateUtils.getRelativeTimeSpanString(parsedDate.getTime(), now, DateUtils.SECOND_IN_MILLIS);
    }
    return "N/A";
}
 
Example 19
Source Project: android_9.0.0_r45   Source File: StorageManagerService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void partitionMixed(String diskId, int ratio) {
    enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
    enforceAdminUser();

    final CountDownLatch latch = findOrCreateDiskScanLatch(diskId);
    try {
        mVold.partition(diskId, IVold.PARTITION_TYPE_MIXED, ratio);
        waitForLatch(latch, "partitionMixed", 3 * DateUtils.MINUTE_IN_MILLIS);
    } catch (Exception e) {
        Slog.wtf(TAG, e);
    }
}
 
Example 20
Source Project: FireFiles   Source File: MediaDocumentsProvider.java    License: Apache License 2.0 5 votes vote down vote up
private void includeImage(MatrixCursor result, Cursor cursor) {
    final long id = cursor.getLong(ImageQuery._ID);
    final String docId = getDocIdForIdent(TYPE_IMAGE, id);

    final RowBuilder row = result.newRow();
    row.add(Document.COLUMN_DOCUMENT_ID, docId);
    row.add(Document.COLUMN_DISPLAY_NAME, cursor.getString(ImageQuery.DISPLAY_NAME));
    row.add(Document.COLUMN_SIZE, cursor.getLong(ImageQuery.SIZE));
    row.add(Document.COLUMN_MIME_TYPE, cursor.getString(ImageQuery.MIME_TYPE));
    row.add(Document.COLUMN_PATH, cursor.getString(ImageQuery.DATA));
    row.add(Document.COLUMN_LAST_MODIFIED,
            cursor.getLong(ImageQuery.DATE_MODIFIED) * DateUtils.SECOND_IN_MILLIS);
    row.add(Document.COLUMN_FLAGS, Document.FLAG_SUPPORTS_THUMBNAIL | Document.FLAG_SUPPORTS_DELETE);
}
 
Example 21
Source Project: cathode   Source File: ApiSettings.java    License: Apache License 2.0 5 votes vote down vote up
@Override public void updateTokens(AccessToken tokens) {
  synchronized (this) {
    final long expirationMillis =
        System.currentTimeMillis() + (tokens.getExpires_in() * DateUtils.SECOND_IN_MILLIS);
    Settings.get(context)
        .edit()
        .putString(TraktLinkSettings.TRAKT_ACCESS_TOKEN, tokens.getAccess_token())
        .putString(TraktLinkSettings.TRAKT_REFRESH_TOKEN, tokens.getRefresh_token())
        .putLong(TraktLinkSettings.TRAKT_TOKEN_EXPIRATION, expirationMillis)
        .apply();
  }
}
 
Example 22
public static String tryParseDescription(Uri conditionUri) {
    final long time = ZenModeConfig.tryParseCountdownConditionId(conditionUri);
    if (time == 0) return null;
    final long now = System.currentTimeMillis();
    final CharSequence span =
            DateUtils.getRelativeTimeSpanString(time, now, DateUtils.MINUTE_IN_MILLIS);
    return String.format("Scheduled for %s, %s in the future (%s), now=%s",
            ts(time), time - now, span, ts(now));
}
 
Example 23
Source Project: twitter-kit-android   Source File: TweetDateUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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
 *
 * @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));
}
 
Example 24
Source Project: mimi-reader   Source File: ThreadListAdapter.java    License: 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 25
Source Project: twitter-kit-android   Source File: SessionMonitorTest.java    License: 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 26
Source Project: YCAudioPlayer   Source File: MusicInfoActivity.java    License: 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 Project: Conquer   Source File: DatePickerDialog.java    License: Apache License 2.0 5 votes vote down vote up
private void updateDisplay(boolean announce) {
       /*if (mDayOfWeekView != null) {
           mDayOfWeekView.setText(mCalendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG,
                   Locale.getDefault()).toUpperCase(Locale.getDefault()));
       }

       mSelectedMonthTextView.setText(mCalendar.getDisplayName(Calendar.MONTH, Calendar.SHORT,
               Locale.getDefault()).toUpperCase(Locale.getDefault()));*/

       if (this.mDayOfWeekView != null){
           this.mCalendar.setFirstDayOfWeek(mWeekStart);
           this.mDayOfWeekView.setText(mDateFormatSymbols.getWeekdays()[this.mCalendar.get(Calendar.DAY_OF_WEEK)].toUpperCase(Locale.getDefault()));
       }

       this.mSelectedMonthTextView.setText(mDateFormatSymbols.getMonths()[this.mCalendar.get(Calendar.MONTH)].toUpperCase(Locale.getDefault()));

       mSelectedDayTextView.setText(DAY_FORMAT.format(mCalendar.getTime()));
       mYearView.setText(YEAR_FORMAT.format(mCalendar.getTime()));

       // 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 28
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 29
Source Project: auth   Source File: CommentsAdapter.java    License: 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 30
Source Project: mua   Source File: FilesAdapter.java    License: 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();
        }
    });
}