Home > OS >  How to remove decimal point in an Java Instant data type
How to remove decimal point in an Java Instant data type

Time:06-01

I get this error whenever I try to remove the decimal point of the Instant datatype in java.

! java.util.IllegalFormatConversionException: M != java.time.Instant

Here is the line of code I am trying to use for the conversion. I am using String.format

subCategory.setSla(Instant.parse(String.format("%tM", Instant.ofEpochSecond(dto.getSla().atZone(ZoneOffset.UTC).getMinute()))));

Without the string format, I get something like 24.00000

I don't want to see the decimal points after 24, how best do you think, it can be handled?

My dto has something like

private Instant sla;

My dto is returning an Instant, that I am very sure of. I want to display just the minute and send just the minute to users in an email. I don't want the default representation with decimal point.

CodePudding user response:

tl;dr

instant                      // Represents a moment as seen in UTC, an offset of zero hours-minutes-seconds. 
.atOffset( ZoneOffset.UTC )  // Returns an `OffsetDateTime` object, converting from `Instant`. 
.getMinute()                 // Returns an `int` primitive value. 

Details

You are conflating date-time objects with text. Classes such as Instant are not text. These classes use their own internally defined representation of date-time values. That representation is not plain text.

Apparently you want to extract just the minute of the hour from an Instant object. That class is a basic building-block class in java.time. So convert to the more flexible OffsetDateTime class.

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;

Extract the minute of hour.

int minute = odt.getMinute() ;

Example:

Instant
.parse( "2023-01-23T19:42:07.123456789Z" )
.atOffset( ZoneOffset.UTC )
.getMinute()

42

  • Related