remake date formatter

This commit is contained in:
Austin Huang 2021-05-23 20:51:29 -04:00
parent 5f217829b8
commit 2395b3b892
No known key found for this signature in database
GPG Key ID: 84C23AA04587A91F
11 changed files with 71 additions and 67 deletions

View File

@ -10,7 +10,7 @@ import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipelineConfig; import com.facebook.imagepipeline.core.ImagePipelineConfig;
import java.net.CookieHandler; import java.net.CookieHandler;
import java.text.SimpleDateFormat; import java.time.format.DateTimeFormatter;
import java.util.UUID; import java.util.UUID;
import awais.instagrabber.fragments.settings.PreferenceKeys; import awais.instagrabber.fragments.settings.PreferenceKeys;
@ -24,7 +24,6 @@ import static awais.instagrabber.utils.CookieUtils.NET_COOKIE_MANAGER;
import static awais.instagrabber.utils.Utils.applicationHandler; import static awais.instagrabber.utils.Utils.applicationHandler;
import static awais.instagrabber.utils.Utils.cacheDir; import static awais.instagrabber.utils.Utils.cacheDir;
import static awais.instagrabber.utils.Utils.clipboardManager; import static awais.instagrabber.utils.Utils.clipboardManager;
import static awais.instagrabber.utils.Utils.datetimeParser;
import static awais.instagrabber.utils.Utils.settingsHelper; import static awais.instagrabber.utils.Utils.settingsHelper;
public final class InstaGrabberApplication extends Application { public final class InstaGrabberApplication extends Application {
@ -78,11 +77,10 @@ public final class InstaGrabberApplication extends Application {
if (clipboardManager == null) if (clipboardManager == null)
clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
if (datetimeParser == null) TextUtils.setFormatter(DateTimeFormatter.ofPattern(
datetimeParser = new SimpleDateFormat(
settingsHelper.getBoolean(PreferenceKeys.CUSTOM_DATE_TIME_FORMAT_ENABLED) ? settingsHelper.getBoolean(PreferenceKeys.CUSTOM_DATE_TIME_FORMAT_ENABLED) ?
settingsHelper.getString(PreferenceKeys.CUSTOM_DATE_TIME_FORMAT) : settingsHelper.getString(PreferenceKeys.CUSTOM_DATE_TIME_FORMAT) :
settingsHelper.getString(PreferenceKeys.DATE_TIME_FORMAT), LocaleUtils.getCurrentLocale()); settingsHelper.getString(PreferenceKeys.DATE_TIME_FORMAT), LocaleUtils.getCurrentLocale()));
if (TextUtils.isEmpty(settingsHelper.getString(Constants.DEVICE_UUID))) { if (TextUtils.isEmpty(settingsHelper.getString(Constants.DEVICE_UUID))) {
settingsHelper.putString(Constants.DEVICE_UUID, UUID.randomUUID().toString()); settingsHelper.putString(Constants.DEVICE_UUID, UUID.randomUUID().toString());

View File

@ -16,10 +16,10 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment; import androidx.fragment.app.DialogFragment;
import java.text.SimpleDateFormat; import java.time.format.DateTimeFormatter;
import java.util.Calendar; import java.time.Instant;
import java.util.Date; import java.time.LocalDateTime;
import java.util.GregorianCalendar; import java.time.ZoneId;
import awais.instagrabber.databinding.DialogTimeSettingsBinding; import awais.instagrabber.databinding.DialogTimeSettingsBinding;
import awais.instagrabber.utils.LocaleUtils; import awais.instagrabber.utils.LocaleUtils;
@ -28,12 +28,12 @@ import awais.instagrabber.utils.TextUtils;
public final class TimeSettingsDialog extends DialogFragment implements AdapterView.OnItemSelectedListener, CompoundButton.OnCheckedChangeListener, public final class TimeSettingsDialog extends DialogFragment implements AdapterView.OnItemSelectedListener, CompoundButton.OnCheckedChangeListener,
View.OnClickListener, TextWatcher { View.OnClickListener, TextWatcher {
private DialogTimeSettingsBinding timeSettingsBinding; private DialogTimeSettingsBinding timeSettingsBinding;
private final Date magicDate; private final LocalDateTime magicDate;
private SimpleDateFormat currentFormat; private DateTimeFormatter currentFormat;
private String selectedFormat; private String selectedFormat;
private boolean customDateTimeFormatEnabled; private final boolean customDateTimeFormatEnabled;
private String customDateTimeFormat; private final String customDateTimeFormat;
private String dateTimeSelection; private final String dateTimeSelection;
private final boolean swapDateTimeEnabled; private final boolean swapDateTimeEnabled;
private final OnConfirmListener onConfirmListener; private final OnConfirmListener onConfirmListener;
@ -47,9 +47,10 @@ public final class TimeSettingsDialog extends DialogFragment implements AdapterV
this.dateTimeSelection = dateTimeSelection; this.dateTimeSelection = dateTimeSelection;
this.swapDateTimeEnabled = swapDateTimeEnabled; this.swapDateTimeEnabled = swapDateTimeEnabled;
this.onConfirmListener = onConfirmListener; this.onConfirmListener = onConfirmListener;
final Calendar instance = GregorianCalendar.getInstance(); magicDate = LocalDateTime.ofInstant(
instance.set(2020, 5, 22, 8, 17, 13); Instant.now(),
magicDate = instance.getTime(); ZoneId.systemDefault()
);
} }
@Override @Override
@ -82,10 +83,9 @@ public final class TimeSettingsDialog extends DialogFragment implements AdapterV
} }
private void refreshTimeFormat() { private void refreshTimeFormat() {
if (timeSettingsBinding.cbCustomFormat.isChecked()) { if (timeSettingsBinding.cbCustomFormat.isChecked())
timeSettingsBinding.btnConfirm.setEnabled(false); selectedFormat = timeSettingsBinding.etCustomFormat.getText().toString();
checkCustomTimeFormat(); else {
} else {
final String sepStr = String.valueOf(timeSettingsBinding.spSeparator.getSelectedItem()); final String sepStr = String.valueOf(timeSettingsBinding.spSeparator.getSelectedItem());
final String timeStr = String.valueOf(timeSettingsBinding.spTimeFormat.getSelectedItem()); final String timeStr = String.valueOf(timeSettingsBinding.spTimeFormat.getSelectedItem());
final String dateStr = String.valueOf(timeSettingsBinding.spDateFormat.getSelectedItem()); final String dateStr = String.valueOf(timeSettingsBinding.spDateFormat.getSelectedItem());
@ -96,24 +96,14 @@ public final class TimeSettingsDialog extends DialogFragment implements AdapterV
selectedFormat = (isSwapTime ? dateStr : timeStr) selectedFormat = (isSwapTime ? dateStr : timeStr)
+ (isBlankSeparator ? " " : " '" + sepStr + "' ") + (isBlankSeparator ? " " : " '" + sepStr + "' ")
+ (isSwapTime ? timeStr : dateStr); + (isSwapTime ? timeStr : dateStr);
}
timeSettingsBinding.btnConfirm.setEnabled(true); timeSettingsBinding.btnConfirm.setEnabled(true);
currentFormat = new SimpleDateFormat(selectedFormat, LocaleUtils.getCurrentLocale());
timeSettingsBinding.timePreview.setText(currentFormat.format(magicDate));
}
}
private void checkCustomTimeFormat() {
try { try {
//noinspection ConstantConditions currentFormat = DateTimeFormatter.ofPattern(selectedFormat, LocaleUtils.getCurrentLocale());
final String string = timeSettingsBinding.etCustomFormat.getText().toString(); timeSettingsBinding.timePreview.setText(magicDate.format(currentFormat));
if (TextUtils.isEmpty(string)) throw new NullPointerException(); }
currentFormat = new SimpleDateFormat(string, LocaleUtils.getCurrentLocale()); catch (Exception e) {
final String format = currentFormat.format(magicDate);
timeSettingsBinding.timePreview.setText(format);
timeSettingsBinding.btnConfirm.setEnabled(true);
} catch (final Exception e) {
timeSettingsBinding.btnConfirm.setEnabled(false); timeSettingsBinding.btnConfirm.setEnabled(false);
timeSettingsBinding.timePreview.setText(null); timeSettingsBinding.timePreview.setText(null);
} }
@ -142,22 +132,19 @@ public final class TimeSettingsDialog extends DialogFragment implements AdapterV
@Override @Override
public void onTextChanged(final CharSequence s, final int start, final int before, final int count) { public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {
checkCustomTimeFormat(); refreshTimeFormat();
} }
@Override @Override
public void onClick(final View v) { public void onClick(final View v) {
if (v == timeSettingsBinding.btnConfirm) { if (v == timeSettingsBinding.btnConfirm) {
final Editable etCustomFormatText = timeSettingsBinding.etCustomFormat.getText();
if (onConfirmListener != null) { if (onConfirmListener != null) {
onConfirmListener.onConfirm( onConfirmListener.onConfirm(
timeSettingsBinding.cbCustomFormat.isChecked(), timeSettingsBinding.cbCustomFormat.isChecked(),
etCustomFormatText == null ? null : etCustomFormatText.toString(),
timeSettingsBinding.spTimeFormat.getSelectedItemPosition(), timeSettingsBinding.spTimeFormat.getSelectedItemPosition(),
timeSettingsBinding.spSeparator.getSelectedItemPosition(), timeSettingsBinding.spSeparator.getSelectedItemPosition(),
timeSettingsBinding.spDateFormat.getSelectedItemPosition(), timeSettingsBinding.spDateFormat.getSelectedItemPosition(),
selectedFormat, selectedFormat,
currentFormat,
timeSettingsBinding.cbSwapTimeDate.isChecked()); timeSettingsBinding.cbSwapTimeDate.isChecked());
} }
dismiss(); dismiss();
@ -170,12 +157,10 @@ public final class TimeSettingsDialog extends DialogFragment implements AdapterV
public interface OnConfirmListener { public interface OnConfirmListener {
void onConfirm(boolean isCustomFormat, void onConfirm(boolean isCustomFormat,
String formatSelection,
int spTimeFormatSelectedItemPosition, int spTimeFormatSelectedItemPosition,
int spSeparatorSelectedItemPosition, int spSeparatorSelectedItemPosition,
int spDateFormatSelectedItemPosition, int spDateFormatSelectedItemPosition,
final String selectedFormat, final String selectedFormat,
final SimpleDateFormat currentFormat,
final boolean swapDateTime); final boolean swapDateTime);
} }

View File

@ -61,7 +61,6 @@ import java.io.IOException;
import java.text.NumberFormat; import java.text.NumberFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -928,7 +927,7 @@ public class StoryViewerFragment extends Fragment {
else setupImage(); else setupImage();
final ActionBar actionBar = fragmentActivity.getSupportActionBar(); final ActionBar actionBar = fragmentActivity.getSupportActionBar();
actionBarSubtitle = Utils.datetimeParser.format(new Date(currentStory.getTimestamp() * 1000L)); actionBarSubtitle = TextUtils.epochSecondToString(currentStory.getTimestamp());
if (actionBar != null) { if (actionBar != null) {
try { try {
actionBar.setSubtitle(actionBarSubtitle); actionBar.setSubtitle(actionBarSubtitle);

View File

@ -7,15 +7,14 @@ import androidx.preference.ListPreference;
import androidx.preference.Preference; import androidx.preference.Preference;
import androidx.preference.PreferenceScreen; import androidx.preference.PreferenceScreen;
import java.text.SimpleDateFormat; import java.time.format.DateTimeFormatter;
import java.util.Date;
import awais.instagrabber.R; import awais.instagrabber.R;
import awais.instagrabber.dialogs.TimeSettingsDialog; import awais.instagrabber.dialogs.TimeSettingsDialog;
import awais.instagrabber.utils.Constants; import awais.instagrabber.utils.Constants;
import awais.instagrabber.utils.LocaleUtils; import awais.instagrabber.utils.LocaleUtils;
import awais.instagrabber.utils.TextUtils;
import awais.instagrabber.utils.UserAgentUtils; import awais.instagrabber.utils.UserAgentUtils;
import awais.instagrabber.utils.Utils;
import static awais.instagrabber.utils.Utils.settingsHelper; import static awais.instagrabber.utils.Utils.settingsHelper;
@ -55,7 +54,7 @@ public class LocalePreferencesFragment extends BasePreferencesFragment {
private Preference getPostTimeFormatPreference(@NonNull final Context context) { private Preference getPostTimeFormatPreference(@NonNull final Context context) {
final Preference preference = new Preference(context); final Preference preference = new Preference(context);
preference.setTitle(R.string.time_settings); preference.setTitle(R.string.time_settings);
preference.setSummary(Utils.datetimeParser.format(new Date())); preference.setSummary(TextUtils.nowToString());
preference.setIconSpaceReserved(false); preference.setIconSpaceReserved(false);
preference.setOnPreferenceClickListener(preference1 -> { preference.setOnPreferenceClickListener(preference1 -> {
new TimeSettingsDialog( new TimeSettingsDialog(
@ -64,15 +63,15 @@ public class LocalePreferencesFragment extends BasePreferencesFragment {
settingsHelper.getString(PreferenceKeys.DATE_TIME_SELECTION), settingsHelper.getString(PreferenceKeys.DATE_TIME_SELECTION),
settingsHelper.getBoolean(PreferenceKeys.SWAP_DATE_TIME_FORMAT_ENABLED), settingsHelper.getBoolean(PreferenceKeys.SWAP_DATE_TIME_FORMAT_ENABLED),
(isCustomFormat, (isCustomFormat,
formatSelection,
spTimeFormatSelectedItemPosition, spTimeFormatSelectedItemPosition,
spSeparatorSelectedItemPosition, spSeparatorSelectedItemPosition,
spDateFormatSelectedItemPosition, spDateFormatSelectedItemPosition,
selectedFormat, selectedFormat,
currentFormat,
swapDateTime) -> { swapDateTime) -> {
settingsHelper.putBoolean(PreferenceKeys.CUSTOM_DATE_TIME_FORMAT_ENABLED, isCustomFormat);
settingsHelper.putBoolean(PreferenceKeys.SWAP_DATE_TIME_FORMAT_ENABLED, swapDateTime);
if (isCustomFormat) { if (isCustomFormat) {
settingsHelper.putString(PreferenceKeys.CUSTOM_DATE_TIME_FORMAT, formatSelection); settingsHelper.putString(PreferenceKeys.CUSTOM_DATE_TIME_FORMAT, selectedFormat);
} else { } else {
final String formatSelectionUpdated = spTimeFormatSelectedItemPosition + ";" final String formatSelectionUpdated = spTimeFormatSelectedItemPosition + ";"
+ spSeparatorSelectedItemPosition + ';' + spSeparatorSelectedItemPosition + ';'
@ -80,10 +79,8 @@ public class LocalePreferencesFragment extends BasePreferencesFragment {
settingsHelper.putString(PreferenceKeys.DATE_TIME_FORMAT, selectedFormat); settingsHelper.putString(PreferenceKeys.DATE_TIME_FORMAT, selectedFormat);
settingsHelper.putString(PreferenceKeys.DATE_TIME_SELECTION, formatSelectionUpdated); settingsHelper.putString(PreferenceKeys.DATE_TIME_SELECTION, formatSelectionUpdated);
} }
settingsHelper.putBoolean(PreferenceKeys.CUSTOM_DATE_TIME_FORMAT_ENABLED, isCustomFormat); TextUtils.setFormatter(DateTimeFormatter.ofPattern(selectedFormat, LocaleUtils.getCurrentLocale()));
settingsHelper.putBoolean(PreferenceKeys.SWAP_DATE_TIME_FORMAT_ENABLED, swapDateTime); preference.setSummary(TextUtils.nowToString());
Utils.datetimeParser = (SimpleDateFormat) currentFormat.clone();
preference.setSummary(Utils.datetimeParser.format(new Date()));
} }
).show(getParentFragmentManager(), null); ).show(getParentFragmentManager(), null);
return true; return true;

View File

@ -1,7 +1,7 @@
package awais.instagrabber.models package awais.instagrabber.models
import awais.instagrabber.repositories.responses.User import awais.instagrabber.repositories.responses.User
import awais.instagrabber.utils.Utils import awais.instagrabber.utils.TextUtils
import java.io.Serializable import java.io.Serializable
import java.util.* import java.util.*
@ -16,7 +16,7 @@ class Comment(
val isChild: Boolean, val isChild: Boolean,
) : Serializable, Cloneable { ) : Serializable, Cloneable {
val dateTime: String val dateTime: String
get() = Utils.datetimeParser.format(Date(timestamp * 1000L)) get() = TextUtils.epochSecondToString(timestamp)
fun getLiked(): Boolean { fun getLiked(): Boolean {
return liked return liked

View File

@ -1,7 +1,7 @@
package awais.instagrabber.models package awais.instagrabber.models
import awais.instagrabber.repositories.responses.User import awais.instagrabber.repositories.responses.User
import awais.instagrabber.utils.Utils import awais.instagrabber.utils.TextUtils
import java.io.Serializable import java.io.Serializable
import java.util.* import java.util.*
@ -16,5 +16,5 @@ data class FeedStoryModel(
val isBestie: Boolean val isBestie: Boolean
) : Serializable { ) : Serializable {
val dateTime: String val dateTime: String
get() = Utils.datetimeParser.format(Date(timestamp * 1000L)) get() = TextUtils.epochSecondToString(timestamp)
} }

View File

@ -1,6 +1,6 @@
package awais.instagrabber.models package awais.instagrabber.models
import awais.instagrabber.utils.Utils import awais.instagrabber.utils.TextUtils
import java.util.* import java.util.*
data class HighlightModel( data class HighlightModel(
@ -11,5 +11,5 @@ data class HighlightModel(
val mediaCount: Int val mediaCount: Int
) { ) {
val dateTime: String val dateTime: String
get() = Utils.datetimeParser.format(Date(timestamp * 1000L)) get() = TextUtils.epochSecondToString(timestamp)
} }

View File

@ -2,7 +2,7 @@ package awais.instagrabber.repositories.responses
import awais.instagrabber.models.enums.MediaItemType import awais.instagrabber.models.enums.MediaItemType
import awais.instagrabber.repositories.responses.feed.EndOfFeedDemarcator import awais.instagrabber.repositories.responses.feed.EndOfFeedDemarcator
import awais.instagrabber.utils.Utils import awais.instagrabber.utils.TextUtils
import java.io.Serializable import java.io.Serializable
import java.util.* import java.util.*
@ -54,7 +54,7 @@ data class Media(
get() { get() {
if (takenAt <= 0) return "" if (takenAt <= 0) return ""
if (dateString != null) return dateString ?: "" if (dateString != null) return dateString ?: ""
dateString = Utils.datetimeParser.format(Date(takenAt * 1000L)) dateString = TextUtils.epochSecondToString(takenAt)
return dateString ?: "" return dateString ?: ""
} }

View File

@ -7,7 +7,7 @@ import java.util.List;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import awais.instagrabber.utils.Utils; import awais.instagrabber.utils.TextUtils;
public class NotificationArgs { public class NotificationArgs {
private final String text; private final String text;
@ -74,7 +74,7 @@ public class NotificationArgs {
@NonNull @NonNull
public String getDateTime() { public String getDateTime() {
return Utils.datetimeParser.format(new Date(Math.round(timestamp * 1000))); return TextUtils.epochSecondToString(Math.round(timestamp));
} }
private String cleanRichText(final String raw) { private String cleanRichText(final String raw) {

View File

@ -4,9 +4,15 @@ import android.content.Context
import android.text.format.DateFormat import android.text.format.DateFormat
import android.text.format.DateUtils import android.text.format.DateUtils
import android.util.Patterns import android.util.Patterns
import java.time.format.DateTimeFormatter
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
import java.util.* import java.util.*
object TextUtils { object TextUtils {
var datetimeParser: DateTimeFormatter = DateTimeFormatter.ofPattern("")
@JvmStatic @JvmStatic
fun isEmpty(charSequence: CharSequence?): Boolean { fun isEmpty(charSequence: CharSequence?): Boolean {
if (charSequence == null || charSequence.length < 1) return true if (charSequence == null || charSequence.length < 1) return true
@ -72,4 +78,25 @@ object TextUtils {
} }
return result return result
} }
@JvmStatic
fun setFormatter(datetimeParser: DateTimeFormatter) {
this.datetimeParser = datetimeParser
}
@JvmStatic
fun epochSecondToString(epochSecond: Long): String {
return LocalDateTime.ofInstant(
Instant.ofEpochSecond(epochSecond),
ZoneId.systemDefault()
).format(datetimeParser)
}
@JvmStatic
fun nowToString(): String {
return LocalDateTime.ofInstant(
Instant.now(),
ZoneId.systemDefault()
).format(datetimeParser)
}
} }

View File

@ -53,7 +53,6 @@ import org.json.JSONObject;
import java.io.File; import java.io.File;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
@ -78,7 +77,6 @@ public final class Utils {
public static final MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); public static final MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
public static final DisplayMetrics displayMetrics = Resources.getSystem().getDisplayMetrics(); public static final DisplayMetrics displayMetrics = Resources.getSystem().getDisplayMetrics();
public static ClipboardManager clipboardManager; public static ClipboardManager clipboardManager;
public static SimpleDateFormat datetimeParser;
public static SimpleCache simpleCache; public static SimpleCache simpleCache;
private static int statusBarHeight; private static int statusBarHeight;
private static int actionBarHeight; private static int actionBarHeight;