android.text.format.DateFormat Java Examples

The following examples show how to use android.text.format.DateFormat. 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: UIHelper.java    From Conversations with GNU General Public License v3.0 6 votes vote down vote up
private static String readableTimeDifference(Context context, long time,
                                             boolean fullDate) {
	if (time == 0) {
		return context.getString(R.string.just_now);
	}
	Date date = new Date(time);
	long difference = (System.currentTimeMillis() - time) / 1000;
	if (difference < 60) {
		return context.getString(R.string.just_now);
	} else if (difference < 60 * 2) {
		return context.getString(R.string.minute_ago);
	} else if (difference < 60 * 15) {
		return context.getString(R.string.minutes_ago, Math.round(difference / 60.0));
	} else if (today(date)) {
		java.text.DateFormat df = DateFormat.getTimeFormat(context);
		return df.format(date);
	} else {
		if (fullDate) {
			return DateUtils.formatDateTime(context, date.getTime(),
					FULL_DATE_FLAGS);
		} else {
			return DateUtils.formatDateTime(context, date.getTime(),
					SHORT_DATE_FLAGS);
		}
	}
}
 
Example #2
Source File: TimePickerSpinnerDelegate.java    From ticdesign with Apache License 2.0 6 votes vote down vote up
private void getHourFormatData() {
    final String bestDateTimePattern = DateFormat.getBestDateTimePattern(mCurrentLocale,
            (mIs24HourView) ? "Hm" : "hm");
    final int lengthPattern = bestDateTimePattern.length();
    mHourWithTwoDigit = false;
    char hourFormat = '\0';
    // Check if the returned pattern is single or double 'H', 'h', 'K', 'k'. We also save
    // the hour format that we found.
    for (int i = 0; i < lengthPattern; i++) {
        final char c = bestDateTimePattern.charAt(i);
        if (c == 'H' || c == 'h' || c == 'K' || c == 'k') {
            mHourFormat = c;
            if (i + 1 < lengthPattern && c == bestDateTimePattern.charAt(i + 1)) {
                mHourWithTwoDigit = true;
            }
            break;
        }
    }
}
 
Example #3
Source File: RecordVoiceButton.java    From jmessage-android-uikit with MIT License 6 votes vote down vote up
private void initDialogAndStartRecord() {
    //存放录音文件目录
    File rootDir = mContext.getFilesDir();
    String fileDir = rootDir.getAbsolutePath() + "/voice";
    File destDir = new File(fileDir);
    if (!destDir.exists()) {
        destDir.mkdirs();
    }
    //录音文件的命名格式
    myRecAudioFile = new File(fileDir,
            new DateFormat().format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".amr");
    if (myRecAudioFile == null) {
        cancelTimer();
        stopRecording();
        Toast.makeText(mContext, mContext.getString(IdHelper.getString(mContext, "jmui_create_file_failed")),
                Toast.LENGTH_SHORT).show();
    }
    Log.i("FileCreate", "Create file success file path: " + myRecAudioFile.getAbsolutePath());
    recordIndicator = new Dialog(getContext(), IdHelper.getStyle(mContext, "jmui_record_voice_dialog"));
    recordIndicator.setContentView(IdHelper.getLayout(mContext, "jmui_dialog_record_voice"));
    mVolumeIv = (ImageView) recordIndicator.findViewById(IdHelper.getViewID(mContext, "jmui_volume_hint_iv"));
    mRecordHintTv = (TextView) recordIndicator.findViewById(IdHelper.getViewID(mContext, "jmui_record_voice_tv"));
    mRecordHintTv.setText(mContext.getString(IdHelper.getString(mContext, "jmui_move_to_cancel_hint")));
    startRecording();
    recordIndicator.show();
}
 
Example #4
Source File: BIGChart.java    From NightWatch with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onTimeChanged(WatchFaceTime oldTime, WatchFaceTime newTime) {
    if (layoutSet && (newTime.hasHourChanged(oldTime) || newTime.hasMinuteChanged(oldTime))) {
        wakeLock.acquire(50);
        final java.text.DateFormat timeFormat = DateFormat.getTimeFormat(BIGChart.this);
        mTime.setText(timeFormat.format(System.currentTimeMillis()));
        showAgoRawBatt();

        if(ageLevel()<=0) {
            mSgv.setPaintFlags(mSgv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
        } else {
            mSgv.setPaintFlags(mSgv.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
        }

        missedReadingAlert();
        mRelativeLayout.measure(specW, specH);
        mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(),
                mRelativeLayout.getMeasuredHeight());
    }
}
 
Example #5
Source File: DataBaseOperations.java    From minx with MIT License 6 votes vote down vote up
public void saveDataInDB(String title, String url, String body) {
    // ' (single apostrophe) doesn't work with sqlite database in insertion, instead of it, use ''(double apostrophe). tldr : store ' as '' otherwise it won't work
    title=title.replace("'","''");
    body=body.replace("'","''");
    Date date = new Date();
    CharSequence initTime = DateFormat.format("yyyy-MM-dd hh:mm:ss", date.getTime());
    String time = initTime.toString();
    DataBaseAdapter dbAdapter = new DataBaseAdapter(context);
    dbAdapter.createDatabase();
    dbAdapter.open();
    String query = "INSERT INTO webpage (title, url, desc, date) " +
            "VALUES ('" + title + "', '" + url + "', '" + body + "', '" + time + "')";
    dbAdapter.executeQuery(query);
    dbAdapter.close();
    Toast.makeText(context, "Data saved successfully", Toast.LENGTH_SHORT).show();
}
 
Example #6
Source File: MapCoverageLayer.java    From trekarta with GNU General Public License v3.0 6 votes vote down vote up
public MapCoverageLayer(Context context, Map map, Index mapIndex, float scale) {
    super(map);
    mContext = context;
    mMapIndex = mapIndex;
    mPresentAreaStyle = AreaStyle.builder().fadeScale(FADE_ZOOM).blendColor(COLOR_ACTIVE).blendScale(10).color(Color.fade(COLOR_ACTIVE, AREA_ALPHA)).build();
    mOutdatedAreaStyle = AreaStyle.builder().fadeScale(FADE_ZOOM).blendColor(COLOR_OUTDATED).blendScale(10).color(Color.fade(COLOR_OUTDATED, AREA_ALPHA)).build();
    mMissingAreaStyle = AreaStyle.builder().fadeScale(FADE_ZOOM).blendColor(COLOR_MISSING).blendScale(10).color(Color.fade(COLOR_MISSING, AREA_ALPHA)).build();
    mDownloadingAreaStyle = AreaStyle.builder().fadeScale(FADE_ZOOM).blendColor(COLOR_DOWNLOADING).blendScale(10).color(Color.fade(COLOR_DOWNLOADING, AREA_ALPHA)).build();
    mSelectedAreaStyle = AreaStyle.builder().fadeScale(FADE_ZOOM).blendColor(COLOR_SELECTED).blendScale(10).color(Color.fade(COLOR_SELECTED, AREA_ALPHA)).build();
    mDeletedAreaStyle = AreaStyle.builder().fadeScale(FADE_ZOOM).blendColor(COLOR_DELETED).blendScale(10).color(Color.fade(COLOR_DELETED, AREA_ALPHA)).build();
    mLineStyle = LineStyle.builder().fadeScale(FADE_ZOOM + 1).color(Color.fade(Color.DKGRAY, 0.6f)).strokeWidth(0.5f * scale).fixed(true).build();
    mTextStyle = TextStyle.builder().fontSize(11 * scale).fontStyle(Paint.FontStyle.BOLD).color(COLOR_TEXT).strokeColor(COLOR_TEXT_OUTLINE).strokeWidth(7f).build();
    mSmallTextStyle = TextStyle.builder().fontSize(8 * scale).fontStyle(Paint.FontStyle.BOLD).color(COLOR_TEXT).strokeColor(COLOR_TEXT_OUTLINE).strokeWidth(5f).build();
    mHillshadesBitmap = getHillshadesBitmap(Color.fade(Color.DKGRAY, 0.8f));
    mPresentHillshadesBitmap = getHillshadesBitmap(Color.WHITE);
    mDateFormat = DateFormat.getDateFormat(context);
    mMapIndex.addMapStateListener(this);
    mAccountHillshades = Configuration.getHillshadesEnabled();
}
 
Example #7
Source File: BgGraphBuilder.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
@Override
public synchronized void onValueSelected(int i, int i1, PointValue pointValue) {
	
	String filtered = "";
	try {
		PointValueExtended pve = (PointValueExtended) pointValue;
		if(pve.calculatedFilteredValue != -1) {
			filtered = " (" + Math.round(pve.calculatedFilteredValue*10) / 10d +")";
		}
	} catch (ClassCastException e) {
		Log.e(TAG, "Error casting a point from pointValue to PointValueExtended", e);
	}
    final java.text.DateFormat timeFormat = DateFormat.getTimeFormat(context);
    //Won't give the exact time of the reading but the time on the grid: close enough.
    Long time = ((long)pointValue.getX())*FUZZER;
    if(tooltip!= null){
        tooltip.cancel();
    }
    tooltip = Toast.makeText(context, timeFormat.format(time)+ ": " + Math.round(pointValue.getY()*10)/ 10d + filtered, Toast.LENGTH_LONG);
    tooltip.show();
}
 
Example #8
Source File: BaseWatchFace.java    From AndroidAPS with GNU Affero General Public License v3.0 6 votes vote down vote up
public void setDateAndTime() {

        final java.text.DateFormat timeFormat = DateFormat.getTimeFormat(BaseWatchFace.this);
        if (mTime != null) {
            mTime.setText(timeFormat.format(System.currentTimeMillis()));
        }

        Date now = new Date();
        SimpleDateFormat sdfHour = new SimpleDateFormat("HH");
        SimpleDateFormat sdfMinute = new SimpleDateFormat("mm");
        sHour = sdfHour.format(now);
        sMinute = sdfMinute.format(now);

        if (mDate != null && mDay != null && mMonth != null) {
            if (sharedPrefs.getBoolean("show_date", false)) {
                SimpleDateFormat sdfDay = new SimpleDateFormat("dd");
                SimpleDateFormat sdfMonth = new SimpleDateFormat("MMM");
                mDay.setText(sdfDay.format(now));
                mMonth.setText(sdfMonth.format(now));
                mDate.setVisibility(View.VISIBLE);
            } else {
                mDate.setVisibility(View.GONE);
            }
        }
    }
 
Example #9
Source File: LibreReceiver.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
public static List<StatusItem> megaStatus() {
    final List<StatusItem> l = new ArrayList<>();
    final Sensor sensor = Sensor.currentSensor();
    if (sensor != null) {
        l.add(new StatusItem("Libre2 Sensor", sensor.uuid + "\nStart: " + DateFormat.format("dd.MM.yyyy kk:mm", sensor.started_at)));
    }
    String lastReading ="";
    try {
        lastReading = DateFormat.format("dd.MM.yyyy kk:mm:ss", last_reading).toString();
        l.add(new StatusItem("Last Reading", lastReading));
    } catch (Exception e) {
        Log.e(TAG, "Error readlast: " + e);
    }
    if (get_engineering_mode()) {
        l.add(new StatusItem("Last Calc.", libre_calc_doku));
    }
    if (Pref.getBooleanDefaultFalse("Libre2_showSensors")) {
        l.add(new StatusItem("Sensors", Libre2Sensors()));
    }
    return l;
}
 
Example #10
Source File: SimpleWavRecorderHandler.java    From CSipSimple with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get the file to record to for a given remote contact. This will
 * implicitly get the current date in file name.
 * 
 * @param remoteContact The remote contact name
 * @return The file to store conversation
 */
private File getRecordFile(File dir, String remoteContact, int way) {
    if (dir != null) {
        // The file name is only to have an unique identifier.
        // It should never be used to store datas as may change.
        // The app using the recording files should rely on the broadcast
        // and on callInfo instead that is reliable.
        String datePart = (String) DateFormat.format("yy-MM-dd_kkmmss", new Date());
        String remotePart = sanitizeForFile(remoteContact);
        String fileName = datePart + "_" + remotePart;
        if (way != (SipManager.BITMASK_ALL)) {
            fileName += ((way & SipManager.BITMASK_IN) == 0) ? "_out" : "_in";
        }
        File file = new File(dir.getAbsoluteFile() + File.separator
                + fileName + ".wav");
        return file;
    }
    return null;
}
 
Example #11
Source File: TrackInformation.java    From trekarta with GNU General Public License v3.0 6 votes vote down vote up
private void updateTrackInformation(Activity activity, Resources resources) {
    Track.TrackPoint ftp = mTrack.points.get(0);
    Track.TrackPoint ltp = mTrack.getLastPoint();

    int pointCount = mTrack.points.size();
    mPointCountView.setText(resources.getQuantityString(R.plurals.numberOfPoints, pointCount, pointCount));

    String distance = StringFormatter.distanceHP(mTrack.getDistance());
    mDistanceView.setText(distance);

    String finish_coords = StringFormatter.coordinates(ltp);
    mFinishCoordinatesView.setText(finish_coords);

    Date finishDate = new Date(ltp.time);
    mFinishDateView.setText(String.format("%s %s", DateFormat.getDateFormat(activity).format(finishDate), DateFormat.getTimeFormat(activity).format(finishDate)));

    long elapsed = (ltp.time - ftp.time) / 1000;
    String timeSpan;
    if (elapsed < 24 * 3600 * 3) { // 3 days
        timeSpan = DateUtils.formatElapsedTime(elapsed);
    } else {
        timeSpan = DateUtils.formatDateRange(activity, ftp.time, ltp.time, DateUtils.FORMAT_ABBREV_MONTH);
    }
    mTimeSpanView.setText(timeSpan);
}
 
Example #12
Source File: NOChart.java    From AndroidAPS with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected void onTimeChanged(WatchFaceTime oldTime, WatchFaceTime newTime) {
    if (layoutSet && (newTime.hasHourChanged(oldTime) || newTime.hasMinuteChanged(oldTime))) {
        wakeLock.acquire(50);
        final java.text.DateFormat timeFormat = DateFormat.getTimeFormat(NOChart.this);
        mTime.setText(timeFormat.format(System.currentTimeMillis()));
        showAgeAndStatus();

        if(ageLevel()<=0) {
            mSgv.setPaintFlags(mSgv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
        } else {
            mSgv.setPaintFlags(mSgv.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
        }

        missedReadingAlert();
        mRelativeLayout.measure(specW, specH);
        mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(),
                mRelativeLayout.getMeasuredHeight());
    }
}
 
Example #13
Source File: TextClock.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Update the displayed time if this view and its ancestors and window is visible
 */
private void onTimeChanged() {
    // mShouldRunTicker always equals the last value passed into onVisibilityAggregated
    if (mShouldRunTicker) {
        mTime.setTimeInMillis(System.currentTimeMillis());
        setText(DateFormat.format(mFormat, mTime));
        setContentDescription(DateFormat.format(mDescFormat, mTime));
    }
}
 
Example #14
Source File: InputHandlers.java    From Android-Shortify with Apache License 2.0 5 votes vote down vote up
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the current time as the default values for the picker
    final Calendar c = Calendar.getInstance();
    int hour = c.get(Calendar.HOUR_OF_DAY);
    int minute = c.get(Calendar.MINUTE);

    // Create a new instance of TimePickerDialog and return it
    return new TimePickerDialog(getActivity(), this, hour, minute,
            DateFormat.is24HourFormat(getActivity()));
}
 
Example #15
Source File: SettingsActivity.java    From heads-up with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
    String stringValue = value.toString();

    if (preference instanceof ClockPreference) {
        final int intValue = (int) value;
        if (intValue < 0) return false; // Not set yet

        int hour = (int) Math.floor(intValue / 60);
        int minute = (int) Math.floor(intValue % 60);

        preference.setSummary(DateFormat.getTimeFormat(preference.getContext()).format(new Date(0, 0, 0, hour, minute)));

    } else if (preference instanceof ListPreference) {
        // For list preferences, look up the correct display value in
        // the preference's 'entries' list.
        ListPreference listPreference = (ListPreference) preference;
        int index = listPreference.findIndexOfValue(stringValue);

        // Set the summary to reflect the new value.
        preference.setSummary(
                index >= 0
                        ? listPreference.getEntries()[index]
                        : null);

    } else {
        // For all other preferences, set the summary to the value's
        // simple string representation.
        preference.setSummary(stringValue);
    }
    return true;
}
 
Example #16
Source File: BgGraphBuilder.java    From NightWatch with GNU General Public License v3.0 5 votes vote down vote up
public Axis previewXAxis(){
    List<AxisValue> previewXaxisValues = new ArrayList<AxisValue>();
    final java.text.DateFormat timeFormat = hourFormat();
    timeFormat.setTimeZone(TimeZone.getDefault());
    for(int l=0; l<=24; l+=hoursPreviewStep) {
        double timestamp = (endHour - (60000 * 60 * l));
        previewXaxisValues.add(new AxisValue((long)(timestamp/fuzz), (timeFormat.format(timestamp)).toCharArray()));
    }
    Axis previewXaxis = new Axis();
    previewXaxis.setValues(previewXaxisValues);
    previewXaxis.setHasLines(true);
    previewXaxis.setTextSize(previewAxisTextSize);
    return previewXaxis;
}
 
Example #17
Source File: LibreReceiver.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
private static double calculateWeightedAverage(List<Libre2RawValue> rawValues, long now) {
    double sum = 0;
    double weightSum = 0;
    DecimalFormat longformat = new DecimalFormat( "#,###,###,##0.00" );

    libre_calc_doku="";
    for (Libre2RawValue rawValue : rawValues) {
        double weight = 1 - ((now - rawValue.timestamp) / (double) SMOOTHING_DURATION);
        sum += rawValue.glucose * weight;
        weightSum += weight;
        libre_calc_doku += DateFormat.format("kk:mm:ss :",rawValue.timestamp) + " w:" + longformat.format(weight) +" raw: " + rawValue.glucose  + "\n" ;
       }
    return Math.round(sum / weightSum);
}
 
Example #18
Source File: HeartbeatFixerUtils.java    From HeartbeatFixerForGCM with Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.KITKAT)
private static void setNextHeartbeatRequest(Context context, int intervalMillis) {
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    long triggerAtMillis = System.currentTimeMillis() + intervalMillis;
    Log.d(TAG, "setNextHeartbeatRequest at: " + DateFormat.format("yyyy-MM-dd hh:mm:ss", triggerAtMillis));
    PendingIntent broadcastPendingIntent = getBroadcastPendingIntent(context);
    int rtcWakeup = AlarmManager.RTC_WAKEUP;
    if (DeviceUtils.hasKitkat()) {
        alarmManager.setExact(rtcWakeup, triggerAtMillis, broadcastPendingIntent);
    } else {
        alarmManager.set(rtcWakeup, triggerAtMillis, broadcastPendingIntent);
    }
}
 
Example #19
Source File: MainActivity.java    From ActivityDiary with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
    super.onQueryComplete(token, cookie, cursor);
    if ((cursor != null) && cursor.moveToFirst()) {
        if (token == QUERY_CURRENT_ACTIVITY_STATS) {
            long avg = cursor.getLong(cursor.getColumnIndex(ActivityDiaryContract.DiaryActivity.X_AVG_DURATION));
            viewModel.mAvgDuration.setValue(getResources().
                    getString(R.string.avg_duration_description, TimeSpanFormatter.format(avg)));

            SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext());
            String formatString = sharedPref.getString(SettingsActivity.KEY_PREF_DATETIME_FORMAT,
                    getResources().getString(R.string.default_datetime_format));

            long start = cursor.getLong(cursor.getColumnIndex(ActivityDiaryContract.DiaryActivity.X_START_OF_LAST));

            viewModel.mStartOfLast.setValue(getResources().
                    getString(R.string.last_done_description, DateFormat.format(formatString, start)));

        }else if(token == QUERY_CURRENT_ACTIVITY_TOTAL) {
            StatParam p = (StatParam)cookie;
            long total = cursor.getLong(cursor.getColumnIndex(ActivityDiaryContract.DiaryStats.DURATION));

            String x = DateHelper.dateFormat(p.field).format(p.end);
            x = x + ": " + TimeSpanFormatter.format(total);
            switch(p.field){
                case Calendar.DAY_OF_YEAR:
                    viewModel.mTotalToday.setValue(x);
                    break;
                case Calendar.WEEK_OF_YEAR:
                    viewModel.mTotalWeek.setValue(x);
                    break;
                case Calendar.MONTH:
                    viewModel.mTotalMonth.setValue(x);
                    break;
            }
        }
    }
}
 
Example #20
Source File: EditAlertActivity.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
static public String timeFormatString(Context context, int hour, int minute) {
    SimpleDateFormat timeFormat24 = new SimpleDateFormat("HH:mm");
    String selected = hour+":" + ((minute<10)?"0":"") + minute;
    if (!DateFormat.is24HourFormat(context)) {
        try {
            Date date = timeFormat24.parse(selected);
            SimpleDateFormat timeFormat12 = new SimpleDateFormat("hh:mm aa");
            return timeFormat12.format(date);
        } catch (final ParseException e) {
            e.printStackTrace();
        }
    }
    return selected;
}
 
Example #21
Source File: BindingActivity.java    From android-speaker-audioanalysis with MIT License 5 votes vote down vote up
private String getFormattedTimeStamp() {

		  	Long tsLong = System.currentTimeMillis();

		    Calendar cal = Calendar.getInstance(Locale.ENGLISH);
		    cal.setTimeInMillis(tsLong);
		    String date = DateFormat.format("dd-MM-yyyy_HH:mm:ss", cal).toString();
		    return date;
		}
 
Example #22
Source File: ObservationViewModel.java    From ground-android with Apache License 2.0 5 votes vote down vote up
public void setObservation(Observation observation) {
  selectedObservation.postValue(observation);

  AuditInfo created = observation.getCreated();
  User createdBy = created.getUser();
  Date creationTime = created.getClientTimeMillis();
  userName.set(createdBy.getDisplayName());
  modifiedDate.set(DateFormat.getMediumDateFormat(application).format(creationTime));
  modifiedTime.set(DateFormat.getTimeFormat(application).format(creationTime));
}
 
Example #23
Source File: TvEpisodesAdapter.java    From CineLog with GNU General Public License v3.0 5 votes vote down vote up
private void setWatchingDataInView(SerieEpisodeDto item, TvEpisodeViewHolder holder) {
    holder.getEpisodeWatchingDate().setText(
            item.getWatchingDate() != null ?
                    DateFormat.getDateFormat(getContext()).format(item.getWatchingDate()) : ""
    );

    if (item.getEpisodeId() != null) {
        holder.getEpisodeWatched().setImageResource(R.drawable.round_eye_purple);
    } else {
        holder.getEpisodeWatched().setImageResource(R.drawable.round_eye_grey);
    }
}
 
Example #24
Source File: DateUtils.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
private static String getLocalizedPattern(String template, Locale locale) {
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
    return DateFormat.getBestDateTimePattern(locale, template);
  } else {
    return new SimpleDateFormat(template, locale).toLocalizedPattern();
  }
}
 
Example #25
Source File: TimePreference.java    From privacy-friendly-interval-timer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public CharSequence getSummary() {
    if (calendar == null) {
        return null;
    }
    return DateFormat.getTimeFormat(getContext()).format(calendar.getTime());
}
 
Example #26
Source File: CVDatePreference.java    From callmeter with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Set date and time as unix time stamp.
 *
 * @param time time stamp
 */
public void setValue(final long time) {
    v.setTimeInMillis(time);
    if (!this.sh) {
        setSummary(getContext().getString(R.string.value) + ": "
                + DateFormat.getDateFormat(getContext()).format(v.getTime()));
    }
    updateDialog();
}
 
Example #27
Source File: CrashHandler.java    From Mupdf with Apache License 2.0 5 votes vote down vote up
private void writeLogcat(String name) {
    CharSequence timestamp = DateFormat.format("yyyyMMdd_kkmmss", System.currentTimeMillis());
    String filename = name + "_" + timestamp + ".log";
    try {
        Logcat.writeLogcat(filename);
    } catch (IOException e) {
        Log.e(TAG, "Cannot write logcat to disk");
    }
}
 
Example #28
Source File: SimpleMonthView.java    From DateTimePicker with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a description for a given virtual view.
 *
 * @param id the day to generate a description for
 * @return a description of the virtual view
 */
private CharSequence getDayDescription(int id) {
    if (isValidDayOfMonth(id)) {
        mTempCalendar.set(mYear, mMonth, id);
        return DateFormat.format(DATE_FORMAT, mTempCalendar.getTimeInMillis());
    }

    return "";
}
 
Example #29
Source File: DateUtil.java    From droidkaigi2016 with Apache License 2.0 5 votes vote down vote up
@NonNull
public static String getMonthDate(Date date, Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), FORMAT_MMDD);
        return new SimpleDateFormat(pattern).format(date);
    } else {
        int flag = DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_NO_YEAR;
        return DateUtils.formatDateTime(context, date.getTime(), flag);
    }
}
 
Example #30
Source File: PieSysInfo.java    From GravityBox with Apache License 2.0 5 votes vote down vote up
private void updateData() {
    mDateText = DateFormat.getMediumDateFormat(mContext).format(new Date()).toUpperCase(Locale.getDefault());
    mNetworkState = mController.getOperatorState();
    if (mNetworkState != null) {
        mNetworkState = mNetworkState.toUpperCase(Locale.getDefault());
    }
    mWifiSsid = getWifiSsid().toUpperCase(Locale.getDefault());
    mBatteryLevelReadable = mController.getBatteryLevel().toUpperCase(Locale.getDefault());
}