java convert date time string to zulu date time format - java

I need to convert this date "2021-09-27 16:32:36" into zulu format like this "yyyy-MM-dd'T'HH:mm:ss.SSS'Z".

tl;dr
"2021-09-27 16:32:36"
.replace( " " , "T" )
.concat( ".Z" )
2021-09-27T16:32:36Z
A fractional second of zero can be omitted under ISO 8601.
String manipulation
Usually I would recommend using java.time classes. But in your case the obvious solution is simple string manipulation, as suggested by Andy Turner.
String iso8601 = "2021-09-27 16:32:36".replace( " " , "T" ).concat( ".000Z" ) ;
I would recommend dropping the zero fractional second. The string would still comply with ISO 8601.
String iso8601 = "2021-09-27 16:32:36".replace( " " , "T" ).concat( "Z" ) ;
The resulting string 2021-09-27T16:32:36Z represents a moment as seen with an offset of zero hours-minutes-seconds ahead/behind UTC.
If you need to do further work, parse that as an Instant. Example: Instant.parse( iso8601 )

Time zone is crucial
The Zulu time that you are asking for defines a definite and precise point in time. The string you have got does not. If we don’t know its time zone, it may denote times in a span of more than 24 hours.
For this answer I am assuming that the time is in US Central time (America/Chicago).
The format you are asking for is ISO 8601.
java.time
Like the other answers I am recommending java.time, the modern Java date and time API, for all of your date and time work. It has good support for ISO 8601.
I am using this formatter for parsing your string:
private static final DateTimeFormatter PARSER
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ROOT);
Now the work goes like this:
ZoneId zone = ZoneId.of("America/Chicago");
String dateString = "2021-09-27 16:32:36";
ZonedDateTime dateTime = LocalDateTime.parse(dateString, PARSER).atZone(zone);
String isoZuluString = dateTime.withZoneSameInstant(ZoneOffset.UTC).toString();
System.out.println(isoZuluString);
Output is:
2021-09-27T21:32:36Z
It’s in ISO 8601 format and in Zulu time, so as far as I am concerned, we’re done. The milliseconds you asked for are not there. They were not in the original string either, and according to the ISO 8601 format they are not mandatory, so you should be fine. Only if you encounter a particularly picky service that requires a fraction of second in the string even when it is .000, use a formatter for producing it:
private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendPattern("'T'HH:mm:ss.SSSX")
.toFormatter(Locale.ROOT);
The formatter could have been written with a format pattern alone. I took this opportunity for demonstrating that we may reuse built-in formatters in our own to make it easier and safer to get ISO 8601 right. Format like this:
String isoZuluString = dateTime.withZoneSameInstant(ZoneOffset.UTC)
.format(FORMATTER);
2021-09-27T21:32:36.000Z
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601

Example with printing on the console :
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class ZuluZulu {
public static void zuluFormatter(String localDateTime) {
String pattern = "yyyy-MM-dd HH:mm:ss";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
String s = localDateTime;
LocalDateTime dt = LocalDateTime.parse(s, formatter);
System.out.println("dateTime Simple Format without T = " + dt.format(formatter));
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS'Z'");
System.out.println("DateTime Zulu format = " + dt.format(formatter2));
}
public static void main(String[] args) {
zuluFormatter("2021-09-27 16:32:36");
}
}
Output :
dateTime Simple Format without T = 2021-09-27 16:32:36
DateTime Zulu format = 2021-09-27 16:32:36.000Z
this example is exactly what you need without printing on the console :
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class ZuluZulu {
public static String zuluFormatter(String localDateTime) {
String pattern = "yyyy-MM-dd HH:mm:ss";
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern(pattern);
String s = localDateTime;
LocalDateTime dt = LocalDateTime.parse(s, formatter);
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-
MM-dd HH:mm:ss.SSS'Z'");
return dt.format(formatter2);
}
public static void main(String[] args) {
System.out.println(zuluFormatter("2021-09-27 16:32:36"));
}
}

Related

Convert UTC datetime to local datetime using java.time

I have a UTC date-time like this (a String): 2022-11-22T17:15:00
And a ZoneID like this: "America/Tijuana"
Using java.time API, I want to get the actual datetime for that zone, which is: 2022-11-22T09:15:00 (the time is 09:15 instead of 17:15)
ZonedDateTime.toLocalDateTime() returns: 2022-11-22T17:15
ZonedDateTime.toString() returns:
2022-11-22T17:15-08:00[America/Tijuana]
None of the above gives me what I'm looking for.
This is my code:
ZoneId zonaID = ZoneId.of('America/Tijuana');
CharSequence dateUTC = "2022-11-22T17:15:00";
LocalDateTime dateTimeL = LocalDateTime.parse(dateUTC);
ZonedDateTime myZDT = ZonedDateTime.now();
ZonedDateTime myZDTFinal = myZDT.of(dateTimeL, zonaID);
System.out.println("using toLocalDateTime: " + myZDTFinal.toLocalDateTime());
System.out.println("using toString: " + myZDTFinal.toString());
I know that this might be a duplicated question but there's so many questions about date-times and I just haven't been able to figure out this.
Any help will be really appreciated.
You have to convert your date to UTC, then convert the convert this zone to your expected zone using withZoneSameInstant like this:
ZonedDateTime toUTCZone = ZonedDateTime.of(dateTimeL, ZoneOffset.UTC);
ZonedDateTime myZDTFinal = toUTCZone.withZoneSameInstant(zonaID);
Output
2022-11-22T09:15-08:00[America/Tijuana]
There can be many ways to achieve the result. A simple approach would be
Parse the given string into LocalDateTime.
Convert it into an OffsetDateTime at UTC using LocalDateTime#atOffset.
Use OffsetDateTime#atZoneSameInstant to convert the resulting OffsetDateTime into a ZonedDateTime at ZoneId.of("America/Tijuana").
Get LocalDateTime out of the resulting ZonedDateTime by using ZonedDateTime#toLocalDateTime.
If required, format this LocalDateTime into the desired string.
LocalDateTime
.parse("2022-11-22T17:15:00") // Parse the given date-time string into LocalDateTime
.atOffset(ZoneOffset.UTC) // Convert it into a ZonedDateTime at UTC
.atZoneSameInstant(ZoneId.of("America/Tijuana")) // Convert the result into a ZonedDateTime at another time-zome
.toLocalDateTime() // Get the LocalDateTime out of the ZonedDateTime
.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss", Locale.ENGLISH))); // If required
Demo:
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
LocalDateTime ldtInTijuana = LocalDateTime.parse("2022-11-22T17:15:00")
.atOffset(ZoneOffset.UTC)
.atZoneSameInstant(ZoneId.of("America/Tijuana"))
.toLocalDateTime();
System.out.println(ldtInTijuana);
// Custom format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
String formatted = ldtInTijuana.format(formatter);
System.out.println(formatted);
}
}
Output:
2022-11-22T09:15
2022-11-22T09:15:00
Note that LocalDateTime#toString removes second and fraction-of-second values if they are zero. Suppose you want to keep them (as you have posted in your question), you can use a DateTimeFormatter as shown above.
An alternate approach:
Alternatively, you can append Z at the end of your ISO 8601 formatted date-time string to enable Instant to parse it and then convert the Instant into a ZonedDateTime corresponding to the ZoneId.of("America/Tijuana") by using Instant#atZone. The symbol, Z refers to UTC in a date-time string.
The rest of the steps will remain the same.
Demo:
public class Main {
public static void main(String[] args) {
String text = "2022-11-22T17:15:00";
text = text + "Z"; // Z refers to UTC
Instant instant = Instant.parse(text);
LocalDateTime ldt = instant.atZone(ZoneId.of("America/Tijuana")).toLocalDateTime();
System.out.println(ldt);
}
}
Output:
2022-11-22T09:15
Learn more about the modern Date-Time API from Trail: Date Time.

Converting one date time format into another in Java

I have a situation where I need to convert one Java date time format into another but have been having just a bear of a time doing so. Been searching for solutions a long time and have tried many things that have just not worked but I'm at my wits end :(.
I have to convert from
yyyy-MM-dd'T'HH:mm:ss
to
MM/dd/yyyy HH:mm:ss
This is the last thing I've tried, but alas it has no effect at all at transforming the pattern:
private Instant convertInstantFormat(Instant incomingDate) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(AUTH_DATE_PATTERN)
.withZone(ZoneId.systemDefault());
return Instant.parse(formatter.format(incomingDate));
}
Where
AUTH_DATE_PATTERN = "MM/dd/yyyy HH:mm:ss";
incomingDate = 2021-10-22T06:39:13Z
and outgoing date = 2021-10-22T06:39:13Z
I'm sure this is probably just the most naive attempt.
I've tried standardizing the date format and then reformatting, but no go.
I'm just sort of out of steam.
As always, any and all help from this incredible community is tremendously appreciated!
UPDATE
I just wanted to point out that the input and output to this method are of type "Instant."
Apologies for not making this clear initially.
I have to convert from yyyy-MM-dd'T'HH:mm:ss to MM/dd/yyyy HH:mm:ss
Your incoming date time format is ISO_LOCAL_DATE_TIME.
String datetime = "2021-12-16T16:22:34";
LocalDateTime source = LocalDateTime.parse(datetime,DateTimeFormatter.ISO_LOCAL_DATE_TIME);
// desired output format
String AUTH_DATE_PATTERN = "MM/dd/yyyy HH:mm:ss";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(AUTH_DATE_PATTERN);
String output = source.format(formatter);
System.out.println(output);
prints
12/16/2021 16:22:34
If your incoming date is 2021-10-22T06:39:13Z that is a zoned date time and can be parsed-from/formatted-to using
DateTimeFormatter.ISO_ZONED_DATE_TIME.
tl;dr
Instant // Represents a point on the time line.
.parse( "2021-10-22T06:39:13Z" ) // Returns an `Instant` object. By default, parses text in standard ISO 8601 for at where `Z` means offset of zero.
.atOffset( ZoneOffset.UTC ) // Returns an `OffsetDateTime` object.
.format(
DateTimeFormatter.ofPattern( "MM/dd/uuuu HH:mm:ss" )
) // Returns a `String` object.
See this code run live at IdeOne.com.
10/22/2021 06:39:13
Details
You said:
incomingDate = 2021-10-22T06:39:13Z
Your formatting pattern fails to match your input string.
Your input string happens to comply with the ISO 8691 format used by default in Instant.parse. So no need to specify a formatting pattern.
Instant instant = Instant.parse( "2021-10-22T06:39:13Z" ) ;
The Z on the end means an offset of zero hours-minutes-seconds from the prime meridian of UTC.
You asked to generate text representing that moment in the format of MM/dd/yyyy HH:mm:ss. I recommend including an indicator of the offset or time zone. But it you insist on omitting that, read on.
Convert from the basic class Instant to the more flexible OffsetDateTime class.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
Specify your formatting pattern.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu HH:mm:ss" ) ;
Generate your desired text.
String output = odt.format( f ) ;
To learn more, search Stack Overflow. These topics have already been addressed many times.
Append timezone 'z' info at the end of the format pattern otherwise parsing throws an exception.
Here's a working example.
Unit Test (Passing)
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class DateFormatConverterTest {
#Test
void convertDate() {
final String incomingDate = "2021-10-22T06:39:13Z";
final String expectedOutgoingDate = "2021/10/22T06:39:13Z";
String actualOutgoingDate = new DateFormatConverter().convertDate(incomingDate);
assertThat(actualOutgoingDate).isEqualTo(expectedOutgoingDate);
}
}
Implementation
import java.time.format.DateTimeFormatter;
public class DateFormatConverter {
private static final DateTimeFormatter INCOMING_DATE_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssz");
private static final DateTimeFormatter OUTGOING_DATE_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy/MM/dd'T'HH:mm:ssz");
String convertDate(String incoming) {
return OUTGOING_DATE_TIME_FORMAT.format(INCOMING_DATE_TIME_FORMAT.parse(incoming));
}
}

DateTimeParseException: Text '2020-04-01T08:53:47.000+02:00 00:00' could not be parsed, unparsed text found at index 29

Getting a DateTimeParseExcpetion when trying to convert the String 2020-04-01T08:53:47.000+02:00 00:00
String date = "2020-04-01T08:53:47.000+02:00 00:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSz");
parsedDate = LocalDateTime.parse(date,formatter).toString();
System.out.println(parsedDate);
Your pattern is not the same as your String. Check the last part where is 000+02:00 00:00.
Your pattern is: SSSz
If you try this:
String date = "2020-04-01T08:53:47.000";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
It will works because your date is like your pattern. Note that every number in the date is into pattern too.
But for your date there is an empty space what no make sense, so removing it, the code works perfectly.
String date = "2020-04-01T08:53:47.000+02:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSz");
Output:
2020-04-01T08:53:47
Note that z is the local time and means "zero hour offset" or "Zulu time" (UTC) and you can use Locale.
The 00:00 at the end of your date-time string doesn't make sense to me. Parse the date-time string after stripping that.
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDate = "2020-04-01T08:53:47.000+02:00 00:00";
strDate = strDate.substring(0, strDate.lastIndexOf(' '));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSz", Locale.ENGLISH);
LocalDateTime parsedDate = LocalDateTime.parse(strDate, formatter);
System.out.println(parsedDate);
OffsetDateTime odt = OffsetDateTime.parse(strDate);
System.out.println(odt);
System.out.println(odt.getOffset());
}
}
Output:
2020-04-01T08:53:47
2020-04-01T08:53:47+02:00
+02:00
Note: You can parse your date-time string (after striping 00:00 from the end of it) to OffsetDateTime in order to preserve the zone-offset information.
Use the built-in formatter
The built-in DateTimeFormatter.ISO_OFFSET_DATE_TIME matches the part of your string that we can understand. And it can parse just that part and ignore the rest.
String date = "2020-04-01T08:53:47.000+02:00 00:00";
ParsePosition pp = new ParsePosition(0);
OffsetDateTime odt = OffsetDateTime.from(
DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(date, pp));
System.out.println("Date and time: " + odt);
System.out.println("Unparsed text: " + date.substring(pp.getIndex()));
Output:
Date and time: 2020-04-01T08:53:47+02:00
Unparsed text: 00:00
Since your string contains an offset from UTC, OffsetDateTime is the correct class to parse into. If we used LocalDateTIme, the offset would be ignored, and we would end up not knowing at which offset the time was to be interpreted, that is, we could not know which point in time it was. With OffsetDateTime the point in time is unambiguous. If you want to convert to the time in your own time zone, convert to ZonedDateTime (still not LocalDateTime).
ZonedDateTime timeInMyTimeZone = odt.atZoneSameInstant(ZoneId.systemDefault());
System.out.println("Date and time: " + timeInMyTimeZone);
Example output:
Date and time: 2020-04-01T11:53:47+05:00[Asia/Aqtobe]
Links
Documentation links:
DateTimeFormatter.ISO_OFFSET_DATE_TIME.
The two-arg DateTimeFormatter.parse​(CharSequence, ParsePosition) that I used.

Java - Date format for Multiple Scenarios

I have a java component to format the date that I retrieve. Here is my code:
Format formatter = new SimpleDateFormat("yyyyMMdd");
String s = "2019-04-23 06:57:00.0";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss.S");
try
{
Date date = simpleDateFormat.parse(s);
System.out.println("Formatter: "+formatter.format(date));
}
catch (ParseException ex)
{
System.out.println("Exception "+ex);
}
The code works great as long as the String s has the format "2019-04-23 06:57:00.0";
My Question is, how to tweak this code so it will work for below scenarios ex,
my s string may have values like
String s = "2019-04-23 06:57:00.0";
or
String s = "2019-04-23 06:57:00";
Or
String s = "2019-04-23";
right now it fails if I don't pass the ms.. Thanks!
Different types
String s = "2019-04-23 06:57:00";
String s = "2019-04-23";
These are two different kinds of information. One is a date with time-of-day, the other is simply a date. So you should be parsing each as different types of objects.
LocalDateTime.parse
To comply with the ISO 8601 standard format used by default in the LocalDateTime class, replace the SPACE in the middle with a T. I suggest you educate the publisher of your data about using only ISO 8601 formats when exchanging date-time values as text.
LocalDateTime ldt1 = LocalDateTime.parse( "2019-04-23 06:57:00".replace( " " , "T" ) ) ;
The fractional second parses by default as well.
LocalDateTime ldt2 = LocalDateTime.parse( "2019-04-23 06:57:00.0".replace( " " , "T" ) ) ;
See this code run live at IdeOne.com.
ldt1.toString(): 2019-04-23T06:57
ldt2.toString(): 2019-04-23T06:57
LocalDate.parse
Your date-only input already complies with ISO 8601.
LocalDate ld = LocalDate.parse( "2019-04-23" ) ;
See this code run live at IdeOne.com.
ld.toString(): 2019-04-23
Date with time-of-day
You can strip out the time-of-day from the date.
LocalDate ld = ldt.toLocalDate() ;
And you can add it back in.
LocalTime lt = LocalTime.parse( "06:57:00" ) ;
LocalDateTime ldt = ld.with( lt ) ;
Moment
However, be aware that a LocalDateTime does not represent a moment, is not a point on the timeline. Lacking the context of a time zone or offset-from-UTC, a LocalDateTime cannot hold a moment, as explained in its class JavaDoc.
For a moment, use the ZonedDateTime, OffsetDateTime, or Instant classes. Teach the publisher of your data to include the offset, preferably in UTC.
Avoid legacy date-time classes
The old classes SimpleDateFormat, Date, and Calendar are terrible, riddled with poor design choices, written by people not skilled in date-time handling. These were supplanted years ago by the modern java.time classes defined in JSR 310.
In case of you have optional parts in pattern you can use [ and ].
For example
public static Instant toInstant(final String timeStr){
final DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH[:mm[:ss[ SSSSSSSS]]]")
.withZone(ZoneId.of("UTC"));
try {
return Instant.from(formatter.parse(timeStr));
}catch (DateTimeException e){
final DateTimeFormatter formatter2 = DateTimeFormatter
.ofPattern("yyyy-MM-dd")
.withZone(ZoneId.of("UTC"));
return LocalDate.parse(timeStr, formatter2).atStartOfDay().atZone(ZoneId.of("UTC")).toInstant();
}
}
cover
yyyy-MM-dd
yyyy-MM-dd HH
yyyy-MM-dd HH:mm
yyyy-MM-dd HH:mm:ss
yyyy-MM-dd HH:mm:ss SSSSSSSS

How to parse date-time with two or three milliseconds digits in java?

Here is my method to parse String into LocalDateTime.
public static String formatDate(final String date) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SS");
LocalDateTime formatDateTime = LocalDateTime.parse(date, formatter);
return formatDateTime.atZone(ZoneId.of("UTC")).toOffsetDateTime().toString();
}
but this only works for input String like
2017-11-21 18:11:14.05
but fails for 2017-11-21 18:11:14.057
with DateTimeParseException.
How can I define a formatter that works for both .SS and .SSS?
You would need to build a formatter with a specified fraction
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd HH:mm:ss")
.appendFraction(ChronoField.MILLI_OF_SECOND, 2, 3, true) // min 2 max 3
.toFormatter();
LocalDateTime formatDateTime = LocalDateTime.parse(date, formatter);
The answers by Basil Bourque and Sleiman Jneidi are excellent. I just wanted to point out that the answer by EMH333 has a point in it too: the following very simple modification of the code in the question solves your problem.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.[SSS][SS]");
The square bracket in the format pattern string enclose optional parts, so this accepts 3 or 2 decimals in the fraction of seconds.
Potential advantage over Basil Bourque’s answer: gives better input validation, will object if there is only 1 or there are four decimals on the seconds (whether this is an advantage depends entirely on your situation).
Advantage over Sleiman Jneidi’s answer: You don’t need the builder.
Possible downside: it accepts no decimals at all (as long as the decimal point is there).
As I said, the other solutions are very good too. Which one you prefer is mostly a matter of taste.
tl;dr
No need to define a formatter at all.
LocalDateTime.parse(
"2017-11-21 18:11:14.05".replace( " " , "T" )
)
ISO 8601
The Answer by Sleiman Jneidi is especially clever and high-tech, but there is a simpler way.
Adjust your input string to comply with ISO 8601 format, the format used by default in the java.time classes. So no need to specify a formatting pattern at all. The default formatter can handle any number of decimal digits between zero (whole seconds) and nine (nanoseconds) for the fractional second.
Your input is nearly compliant. Just replace the SPACE in the middle with aT.
String input = "2017-11-21 18:11:14.05".replace( " " , "T" );
LocalDateTime ldt = LocalDateTime.parse( input );
ldt.toString(): 2017-11-21T18:11:14.050
Using Java 8 you can use the DateTimeFormatterBuilder and a Pattern. See this answer for a little more information
public static String formatDate(final String date) {
DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ofPattern("" + "[yyyy-MM-dd HH:mm:ss.SSS]"
+ "[yyyy-MM-dd HH:mm:ss.SS]"));
DateTimeFormatter formatter = dateTimeFormatterBuilder.toFormatter();
try {
LocalDateTime formatDateTime = LocalDateTime.parse(date, formatter);
return formatDateTime.atZone(ZoneId.of("UTC")).toOffsetDateTime().toString();
} catch (DateTimeParseException e) {
return "";
}
}
Ideally, you would account for a time that has 0 nanoseconds as well. If the time so happens to land perfectly on 2021-02-28T12:00:15.000Z, it may actually be serialised to 2021-02-28T12:00:15Z (at least, for something like java.time.OffsetDateTime it would be). It would therefore be more appropriate to use the following:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS][.SS][.S]");
... and if you require time zone, like I did, then it would look this:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS][.SS][.S]z");
DateTimeFormatter allows specifying optional units using square brackets.
Demo:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"yyyy-MM-dd HH:mm:ss[.[SSSSSSSSS][SSSSSSSS][SSSSSSS][SSSSSS][SSSSS][SSSS][SSS][SS][S]]",
Locale.ENGLISH);
// Test
Stream.of(
"2015-05-04 12:34:56.123456789",
"2015-05-04 12:34:56.123456",
"2015-05-04 12:34:56.123",
"2015-05-04 12:34:56"
).forEach(s -> System.out.println(LocalDateTime.parse(s, formatter)));
}
}
Output:
2015-05-04T12:34:56.123456789
2015-05-04T12:34:56.123456
2015-05-04T12:34:56.123
2015-05-04T12:34:56
Learn more about the modern date-time API from Trail: Date Time.

Categories

Resources