简体   繁体   English

如何删除 Java Instant 数据类型中的小数点

[英]How to remove decimal point in an Java Instant data type

I get this error whenever I try to remove the decimal point of the Instant datatype in java.每当我尝试在 java 中删除 Instant 数据类型的小数点时,都会收到此错误。

! 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我正在使用 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没有字符串格式,我得到类似24.00000

I don't want to see the decimal points after 24, how best do you think, it can be handled?我不想看到24后的小数点,你觉得怎么处理最好?

My dto has something like我的 dto 有类似的东西

private Instant sla;

My dto is returning an Instant , that I am very sure of.我的 dto 正在返回一个Instant ,我非常确定。 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.我不想要带小数点的默认表示。

tl;dr tl;博士

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. Instant等类不是文本。 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.显然,您只想从Instant对象中提取小时的分钟。 That class is a basic building-block class in java.time .该类是java.time中的基本构建块类。 So convert to the more flexible OffsetDateTime class.所以转换为更灵活的OffsetDateTime类。

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 42

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM