I would recommend using parsers for parsing and amending dynamic JSON data. However, if the JSON is static and you want to achieve your result using regex; then your regex is very correct(although it can be compacted. See in answer). You just need to use LocalDateTime
instance instead of LocalDate
instance. Something like;
// Sample code. Please manipulate according to your requirements.
import java.time.*;
public class Main
{
public static void main(String[] args) {
// Sample test String
String content = "\"buyDate\":\"2019-04-09T13:21:00.866Z\"";
// String result = content.replaceAll("(\"buyDate\":\"(\\d{4}-\\d{2}-\\d{2}.*)\")", "\"buyDate\":\""
//+ LocalDateTime.now().toString() + "Z\"");
// COMPACTED REGEX
String result = content.replaceAll("(\"buyDate\":\".*?\"", "\"buyDate\":\""
+ LocalDateTime.now().toString() + "Z\"");
System.out.println(result);
}
}
// Outputs: "buyDate":"2020-06-16T09:33:38.276Z" a.t. online IDE's local time.
You can find the sample run of the above code in here.
If you want to replace only date value leaving time and zero-hour format as it is(although I don't see any practical reason to do so); then you could try this:
import java.time.*;
import java.time.format.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main
{
public static void main(String[] args) {
LocalDate dt = LocalDate.now();
final String regex = "\"buyDate\":\"(\\d{4}-\\d{2}-\\d{2})T";
final String string = "\"buyDate\":\"2019-04-09T13:21:00.866Z\"";
DateTimeFormatter formatDateToday=DateTimeFormatter.ofPattern("YYYY-MM-dd");
final String subst = "\"buyDate\":\""+ dt.format(formatDateToday) +"T";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);
System.out.println(result);
}
}
- I used
DateTimeFormatter
class for formatting the Date.
- I used
Pattern
and Matcher
class to match only the dates in the given JSON string.
You can find the sample run of the above code in here.