The Answer by daggett using regex is slick. If curious, here is the date-time way to handle it.
java.time
xxx_05102019023601017.csv
I am assuming the digits represent day-of-month, month, year, hour, minute, second, millisecond.
Input
Split your string on the underscore by calling String::split
.
String input = "foobar_05102019023601017.csv" ;
String[] parts = string.split( "_" ) ;
String part1 = parts[0]; // foobar
String part2 = parts[1]; // 05102019023601017.csv
Define a formatter to match the second part.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "ddMMuuuuHHmmssSSS'.csv'" ) ;
Parse as a LocalDateTime
object, since your input lacks any indicator of time zone or offset-from-UTC.
LocalDateTime ldt = LocalDateTime.parse( part2 , f ) ;
Output
Define a formatter for the output.
DateTimeFormatter formatterOutput = DateTimeFormatter.ofPattern( "uuuuMMddHHmmssSSS" ) ;
Generate output.
String datetimeOutput = ldt.format( formatterOutput ) ;
String prefix = part1 + "_" ;
String suffix = ".csv" ;
String output = prefix + datetimeOutput + suffix ;
Or more succinctly, use a StringBuilder
for a single-liner.
String output = new StringBuilder()
.append( part1 )
.append( "_" )
.append( ldt.format( formatterOutput ) )
.append( ".csv")
.toString()
;
ISO 8601
Your format is close to the “basic” variation of standard ISO 8601 format. I suggest using these standard formats wherever feasible. To comply, insert a T
between the year-month-day portion and the hour-minute-second portion.
To do so, change the DateTimeFormatter
pattern. Insert the letter inside a pair of single-quotes: 'T'
.
DateTimeFormatter formatterOutput = DateTimeFormatter.ofPattern( "uuuuMMdd'T'HHmmssSSS" ) ;
Zone/Offset
A date and a time without an assigned time zone or offset-from-UTC is ambiguous and therefore prone to misinterpretation. I suggest always including the zone or offset to communicate clearly.
If this date and time was meant to represent a moment in UTC (a good idea generally), append simply a Z
. This letter means UTC, or an offset of zero hours-minutes-seconds. The letter is pronounced “Zulu”.
String output = new StringBuilder()
.append( part1 )
.append( "_" )
.append( ldt.format( formatterOutput ) )
.append( "Z" )
.append( ".csv")
.toString()
;