Reputation: 451
I have 2 times SimpleDateFormat :
How to check if the time use "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" or "yyyy-MM-dd'T'HH:mm:ss'Z'" ?
example :
if ("2020-11-23T21:17:03.039023Z".contentEquals("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")) {
Log.e("TAG", "true");
} else {
Log.e("TAG", "false");
}
Upvotes: 1
Views: 82
Reputation: 79095
You can parse the date-time string to Instant
and check if the fraction of second is greater than 0
.
import java.time.DateTimeException;
import java.time.Instant;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(isTagEnabled("2020-11-23T21:17:03.039023Z"));
System.out.println(isTagEnabled("2020-11-23T21:17:03Z"));
}
static boolean isTagEnabled(String strDateTime) {
boolean enbaled = false;
try {
if (Instant.parse(strDateTime).getNano() > 0) {
enbaled = true;
}
} catch (DateTimeException e) {
e.printStackTrace();
}
return enbaled;
}
}
Output:
true
false
Based on this, you can write your code as
if (isTagEnabled("2020-11-23T21:17:03.039023Z")) {
Log.e("TAG", "true");
} else {
Log.e("TAG", "false");
}
Note that the date-time API of java.util
and their formatting API, SimpleDateFormat
are outdated and error-prone. I suggest you should stop using them completely and switch to the modern date-time API.
Learn more about the modern date-time API at Trail: Date Time. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Upvotes: 1
Reputation: 521457
You probably want String#matches
here with an appropriate regex pattern:
String dt = "2020-11-23T21:17:03.039023Z";
String regex = "\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{6}Z";
if (dt.matches(regex)) {
Log.e("TAG", "true");
}
else {
Log.e("TAG", "false");
}
But note that the above does not actually do any validation on the input, but rather just detects the general pattern, and distinguishes from the version with no millisecond/microsecond precision.
Upvotes: 2