Home > database >  Adding a char after a certain value and condition of string Java
Adding a char after a certain value and condition of string Java

Time:08-11

I have this pattern of date: 2000-03-05 represented by YYYY-MM-dd

The problem is, the date value can be empty, so I would get "2000-03-".

I was trying to override this behavior by using replace all, to replace the null value, but as I get the value in String, there is no null or empty value.

String.join("-", date.getYear(), date.getMonth(), date.getDay()).replaceAll(" ", "c")

How should this be done?

Thanks!

CodePudding user response:

You could probably use a Conditional Operator aka, the ternary (?:) operator where (a ? b : c) says if a is true, evaluate b, else evaluate c. and do it like this.

String.join("-", date.getYear(), date.getMonth(), 
     date.getDay().isEmpty() ? "c" : date.getDay());

Here's an example using a record as a simple Date class.

record Date(String getYear, String getMonth, String getDay) {

Date date1 = new Date("2002", "10", "30");
Date date2 = new Date("2002", "10", "");

System.out.println(String.join("-", date1.getYear(),
        date1.getMonth(),
        date1.getDay().isEmpty() ? "c" : date1.getDay()));

System.out.println(String.join("-", date2.getYear(),
        date2.getMonth(),
        date2.getDay().isEmpty() ? "c" : date2.getDay()));

prints

2002-10-30
2002-10-c

But you may want to provide more information including your use case as more constructive help could result. And make certain you aren't using the old Date class but those classes in the java.time package.

CodePudding user response:

In addition to WJS comment, I would have put everything in a String.format in order to make things clearer and more readable.

String.format("%s-%s-%s", date1.getYear(), date1.getMonth(), date1.getDay().isEmpty() ? "c" : date1.getDay());

CodePudding user response:

You can use SimpleDateFormat as below:

String sDate ="2020-08-";  
Date date = null;
try {
    date = new SimpleDateFormat("yyyy-MM-dd").parse(sDate);
} catch (ParseException e) {
    // TODO Auto-generated catch block
    sDate = sDate   "c";
}  
System.out.println("sDate= "  "\t"  sDate);

Output: sDate= 2020-08-c

  • Related