I'm trying to take a date and pad it with 0's on the left so I can parse it as a date.
static LocalDate cleanDate(String s)
{
s = s.replace(',', '-');
String[] str = s.split("-");
String.format("%1$" 2 "s", str[0]).replace(' ', '0');
}
Initially the string coming in looks like this: "11-2,2020" I need to pad the month and date with 0's on the left so it looks like this "11-02-2020" so I can use my date formatter "MM-dd-yyyy".
Java is unhappy with me passing str[0] and wants it to be an Object[] instead of a String. Every "how to" that I've run into use passing a string in this portion, in fact I have copy pasted several variations of allegedly working code and simply replaced their "input string" or whatever with mine. I keep getting this error. I'm sure I'm doing something stupid, but I'm not sure what is.
Thanks in advance.
CodePudding user response:
java.time
Let the java.time framework do the heavy-lifting here. See tutorial by Oracle.
Define a formatter to match your input.
DateTimeFormatter fInput = DateTimeFormatter.ofPattern( "M-d,uuuu" )
Parse.
LocalDate ld = LocalDate.parse( input , fInput ) ;
Define a formatter to match your desired output.
DateTimeFormatter fOutput = DateTimeFormatter.ofPattern( "MM-dd-uuuu" ) ;
Generate text.
String output = ld.format( fOutput ) ;
See this code run at Ideone.com.
CodePudding user response:
Instead of manipulating your string, you can maybe make a parser that fits your needs. For example
String textDate = "11-2,2020";
SimpleDateFormat parser = new SimpleDateFormat("MM-dd,yyyy");
Date date = parser.parse(textDate);
If you need to switch back to text format, you can use another formatter
SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
System.out.println(formatter.format(date));
2 points of attention with the SimpleDateFormat object 1/ It is not threadSafe, so be careful if you use it in a multithreaded context (web service for example) 2/ It's heavy to instantiate, it's better to instantiate it once for all rather than at each call