I want to remove sub string from my string which is dynamic date time.
Example:
Nov 19, 2019 05:41:08 AM EST
I need:
Nov 19, 2019 05 AM EST this kind of string
I want to remove minutes and second from the string.
You may try a regex string replacement:
String input = "Nov 19, 2019 05:41:08 AM EST";
String output = input.replaceAll("\\b(\\d{2}):\\d{2}:\\d{2}\\b", "$1");
System.out.println(output);
This prints:
Nov 19, 2019 05 AM EST
A perhaps more robust approach would be to go back to the Date, LocalDate/LocalDateTime which generated the current output and instead format using the new mask you want.
You can use regex to remove everything between the first : and the first blank space
String original = "Nov 19, 2019 05:41:08 AM EST";
String stripped = original.replaceAll(":.*? ", " ");
System.out.print(stripped); // prints Nov 19, 2019 05 AM EST
original.replaceAll(":.*?(?= )", "");If you are not comfortable with RegEx, you can use the following solution:
public class Main {
public static void main(String[] args) {
String dateString="Nov 19, 2019 05:41:08 AM EST";
String requiredString=dateString.replace(dateString.substring(dateString.indexOf(':'),dateString.indexOf(' ',dateString.indexOf(':'))),"");
System.out.println(requiredString);
}
}
Output:
Nov 19, 2019 05 AM EST
There are many other ways as well e.g. using DateTimeFormatter