-2

I want to remove square brackets for this one. I tried it but it gives same output.

String datetime = [Thu Sep 14 17:00:00 GMT+05:30 2017];
datetime=datetime.replaceAll("\\[", "").replaceAll("\\]","");

Where am I going wrong?

cs95
  • 379,657
  • 97
  • 704
  • 746
sri
  • 7
  • 1

2 Answers2

-1

If you're already setting the datetime String on your own, why don't you just set it without square brackets? String datetime = "Thu Sep 14 17:00:00 GMT+05:30 2017";

And you're supposed to have a compiler error because your String datetime is not valid, because it has no double quotes.

On the other hand if you receive a data for datetime String from Java class Date then you can change the format of the data you're receiving with SimpleDateFormat.

If you do not know how to use SimpleDateFormat, check it out here

Here's some brief example of it and you can check full tutorial here:

public class GetCurrentDateTime {

private static final DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");

public static void main(String[] args) {

    Date date = new Date();
    System.out.println(sdf.format(date));

    Calendar cal = Calendar.getInstance();
    System.out.println(sdf.format(cal.getTime()));

    LocalDateTime now = LocalDateTime.now();
    System.out.println(dtf.format(now));

    LocalDate localDate = LocalDate.now();
    System.out.println(DateTimeFormatter.ofPattern("yyy/MM/dd").format(localDate));

}

}

Strahinja
  • 440
  • 9
  • 26
  • This definitely isn't your code... – cs95 Sep 14 '17 at 09:31
  • It's not, so what? I could wrote it by myself and it would pretty similar and the point is the same, I just wanted to give fast and clear answer. – Strahinja Sep 14 '17 at 09:43
  • The whole point was to link/accredit any external reference, and you seem to have done that based on my comment, which is what I wanted. I rest my case. No need to get defensive. – cs95 Sep 14 '17 at 09:44
-1

Don't replace brackets with nothing, match inside of brackets with regex, then replace whole string with inside part.

Like this

String datetime = "[Thu Sep 14 17:00:00 GMT+05:30 2017]";
datetime=datetime.replaceAll("\\[(.*)\\]", "$1");
System.out.println( datetime); // output is: Thu Sep 14 17:00:00 GMT+05:30 2017
Rahmat Waisi
  • 1,293
  • 1
  • 15
  • 36