Removing nanoseconds in a date string

What I'm trying to achieve ...

I have dates in potentially 2 formats:

2013-07-03T14:30:38Z
2013-07-03T14:30:38.000000Z

I want to omit .00000if it exists

I went so far as to delete everything after the ".". time.replaceFirst ( "^(.*?)\\b\\..*$", "$ 1");

result: 2013-07-03T14:30:38

The problem is that I still need a " Z". How can i save Z?

I am not an expert on time time ...

so I'm not quite sure that there will always be 6 0s (if the string contains nanoseconds) or there may be a variable number 0s ...

Java 8

I use java, but don't want to mark it as java, since basically it is just a pure regex

+4
source share
3 answers

I use java, but don't want to mark it as java, since basically it is just a pure regex

, java.time,
:

time.replaceFirst( "\\.\\d*(Z)?$", "$1");
+1

Z :

time.replaceFirst( "^(.*?)\\b\\..*$", "$1Z");

, (.):

time.replaceFirst( "^([^.]+).*(Z)$", "$1$2");
+3

!= -

: (-) , "". String.

, "$ 12.34" , . .

. , , .

java.time

Java 8 java.time framework (Tutorial). , , . , .

ISO 8601. , millisecond (3 ), java.time nanosecond ( 9 ).

java.time Framework ISO 8601 . , ISO 8601.

An Instant UTC. , ZonedDateTime, . .

String input = "2013-07-03T14:30:38.123456789Z";
Instant instant = Instant.parse( input );

Instant. , with, . , java.time . .

Instant instantTruncated = instant.with( ChronoField.NANO_OF_SECOND , 0 );

, , DateTimeFormatter.ISO_INSTANT. , . …7.12 …7.120, …7.1234 …7.123400 …7.0 …7. .

DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
String output = formatter.format( instantTruncated );

Method toStringon Instantthe default formatter uses DateTimeFormatter.ISO_INSTANT. So technically we could shorten the code just to make a call toString. But I want to explicitly indicate how the formatter is involved.

Dump for the console.

System.out.println( "instant: " + instant );
System.out.println( "instantTruncated: " + instantTruncated );
System.out.println( "output: " + output );

At startup.

instant: 2013-07-03T14:30:38.123456789Z
instantTruncated: 2013-07-03T14:30:38Z
output: 2013-07-03T14:30:38Z

We can assign a time zone to this Instant to get "ZonedDateTime".

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instantTuncated , zoneId);
+3
source

Source: https://habr.com/ru/post/1609340/


All Articles