Skip to content

Commit f0f1169

Browse files
fix: date parsing bug #773
1 parent 3daba0a commit f0f1169

File tree

2 files changed

+49
-14
lines changed

2 files changed

+49
-14
lines changed

MobileBuy/buy3/src/main/java/com/shopify/buy3/Utils.java

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -31,22 +31,27 @@
3131
import java.util.Locale;
3232

3333
final class Utils {
34-
private static final SimpleDateFormat DATE_TIME_FORMATTER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US);
35-
36-
static Date parseDateTime(String dateTime) {
37-
try {
38-
Instant instant = Instant.parse(dateTime);
39-
return Date.from(instant);
40-
} catch(Exception e1) {
41-
// Fallback to legacy parsing in case of exception
34+
private static final SimpleDateFormat Z_DATE_TIME_FORMATTER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US);
35+
private static final SimpleDateFormat DATE_TIME_FORMATTER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
36+
37+
static Date parseDateTime(String dateTime) {
38+
try {
39+
return Z_DATE_TIME_FORMATTER.parse(dateTime);
40+
} catch (Exception ignored) {}
41+
4242
try {
43-
return DATE_TIME_FORMATTER.parse(dateTime);
44-
} catch (ParseException e2) {
45-
return new Date();
43+
// Fixes: https://github.com/Shopify/mobile-buy-sdk-android/issues/773
44+
return DATE_TIME_FORMATTER.parse(dateTime);
45+
} catch (ParseException ignored) {}
46+
47+
try {
48+
49+
return DATE_TIME_FORMATTER.parse(new Date().toString());
50+
} catch (ParseException e) {
51+
return new Date() ;
4652
}
4753
}
48-
}
4954

50-
private Utils() {
51-
}
55+
private Utils() {
56+
}
5257
}

MobileBuy/buy3/src/test/java/com/shopify/buy3/Utils.kt

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,13 @@
2424
package com.shopify.buy3
2525

2626
import org.junit.Assert
27+
import org.junit.Test
28+
import java.text.SimpleDateFormat
29+
import java.util.Calendar
30+
import java.util.Date
31+
import java.util.TimeZone
32+
import java.util.concurrent.TimeUnit
33+
import kotlin.math.abs
2734

2835
internal fun checkForIllegalArgumentException(action: () -> Unit) {
2936
try {
@@ -32,4 +39,27 @@ internal fun checkForIllegalArgumentException(action: () -> Unit) {
3239
} catch (e: IllegalArgumentException) {
3340
// ignore
3441
}
42+
}
43+
44+
class UtilsTest {
45+
@Test
46+
fun testDateTimeParsingWithZFormat() {
47+
val parsedDate = Utils.parseDateTime("2022-07-06T12:51:06Z")
48+
Assert.assertEquals(
49+
"Parsing returns current time instead of actual date",
50+
"Wed Jul 06 12:51:06 BST 2022",
51+
parsedDate.toString()
52+
)
53+
}
54+
55+
@Test
56+
fun testDateTimeParsingWithoutZFormat() {
57+
val testDateStr = "2023-02-03T15:11:06"
58+
59+
Assert.assertEquals(
60+
"Parsed date should match expected timestamp",
61+
1675437066000,
62+
Utils.parseDateTime(testDateStr).time
63+
)
64+
}
3565
}

0 commit comments

Comments
 (0)