0

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.

0

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

Thank you very much Guy, your solution work for me String original = "Nov 19, 2019 05:41:08 AM EST"; String stripped = original.replaceAll(":.*? ", " "); System.out.print(stripped);
Or maybe original.replaceAll(":.*?(?= )", "");
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.