Executive answer: No, String.replaceAll
will not work for converting your datetime nor your date to UTC.
Java (and Java 8 and later in particular) has very good support for parsing, handling, converting and formatting dates and times. For example:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
DateTimeFormatter timestampFormatter = DateTimeFormatter
.ofPattern("dd/MM/yyyy hh:mm:ss.SSSSSS a XXX", Locale.ENGLISH);
String dateString = "06/04/2019";
String timestampString = "15/03/2018 03:46:59.000386 PM -05:00";
OffsetDateTime timestampOnDate = OffsetDateTime
.parse(timestampString, timestampFormatter)
.with(LocalDate.parse(dateString, dateFormatter));
System.out.println("Output: " + timestampOnDate.format(timestampFormatter));
System.out.println("Output in UTC: "
+ timestampOnDate.withOffsetSameInstant(ZoneOffset.UTC)
.format(timestampFormatter));
This prints:
Output: 06/04/2019 03:46:59.000386 PM -05:00
Output in UTC: 06/04/2019 08:46:59.000386 PM Z
Your strings and formats didn’t quite make sense, so I have changed them a bit: MM/dd
to dd/MM
, 15 PM to 03 PM and therefore also HH
(for hour of day) to hh
(for hour within AM or PM). If these changes were not the correct ones, just make the ones you want instead.
Edit: Of course, if you insist, you may do
timestampString = timestampString.replaceFirst("^\\d{2}/\\d{2}/\\d{4}", dateString);
— to obtain 06/04/2019 03:46:59.000386 PM -05:00
and then parse as before. I consider this code less readable, and it also won’t give you the validation of the date that was in the timestamp string at first. I recommend using the date-time classes for manipulating your date and timestamp as I do in the code example.