Skip to content

Commit

Permalink
[DatePicker] Fix time zone when custom text input format is set
Browse files Browse the repository at this point in the history
Resolves #3338

GIT_ORIGIN_REV_ID=bb3760f22753b10608d5bd1b342b5b063b3276bb
PiperOrigin-RevId: 523792669
  • Loading branch information
pubiqq authored and drchen committed Apr 13, 2023
1 parent 9ffaa8d commit 619d5a6
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 1 deletion.
Expand Up @@ -192,6 +192,10 @@ public int getDefaultTitleResId() {

@Override
public void setTextInputFormat(@Nullable SimpleDateFormat format) {
if (format != null) {
format = (SimpleDateFormat) UtcDates.getNormalizedFormat(format);
}

this.textInputFormat = format;
}

Expand Down
Expand Up @@ -96,6 +96,10 @@ public Long getSelection() {

@Override
public void setTextInputFormat(@Nullable SimpleDateFormat format) {
if (format != null) {
format = (SimpleDateFormat) UtcDates.getNormalizedFormat(format);
}

this.textInputFormat = format;
}

Expand Down
Expand Up @@ -149,13 +149,19 @@ private static DateFormat getFormat(int style, Locale locale) {
return format;
}

static DateFormat getNormalizedFormat(@NonNull DateFormat dateFormat) {
DateFormat clone = (DateFormat) dateFormat.clone();
clone.setTimeZone(getTimeZone());
return clone;
}

static SimpleDateFormat getDefaultTextInputFormat() {
String defaultFormatPattern =
((SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()))
.toPattern()
.replaceAll("\\s+", "");
SimpleDateFormat format = new SimpleDateFormat(defaultFormatPattern, Locale.getDefault());
format.setTimeZone(UtcDates.getTimeZone());
format.setTimeZone(getTimeZone());
format.setLenient(false);
return format;
}
Expand Down
Expand Up @@ -23,6 +23,7 @@
import androidx.appcompat.app.AppCompatActivity;
import androidx.test.core.app.ApplicationProvider;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
Expand Down Expand Up @@ -83,4 +84,15 @@ public void textInputHintForKorean() {

assertEquals("년.월.일.", hint);
}

@Test
public void normalizeTextInputFormat() {
SimpleDateFormat sdf = new SimpleDateFormat("M/d/y");
sdf.setTimeZone(TimeZone.getTimeZone("US/Pacific"));

SimpleDateFormat normalized = (SimpleDateFormat) UtcDates.getNormalizedFormat(sdf);

assertEquals(TimeZone.getTimeZone("US/Pacific"), sdf.getTimeZone());
assertEquals(TimeZone.getTimeZone("UTC"), normalized.getTimeZone());
}
}

0 comments on commit 619d5a6

Please sign in to comment.