gpt4 book ai didi

java - 有没有办法将纳秒时间转换为不带零的字符串?

转载 作者:行者123 更新时间:2023-11-30 04:22:17 27 4
gpt4 key购买 nike

预期结果是“最后一场比赛 2 小时 12 分钟前”。或“最后一场比赛 3 分钟前。”。

目前它是“最后一场比赛 0d 2h 12m 前。”,我在 SimpleDateFormat 中找不到任何可以做到这一点的东西,我看到的最简单的解决方案是使用 StringBuilder,每次测试值是否为零。

代码示例:

public String getLastgame()
{
long time = ((System.currentTimeMillis() / 60000) - this.config.getLastgameTime());

return ("Last game " + (time / 60) + "h " + (time % 60) + "m ago.");
}

最佳答案

您的时间以分钟为单位,因此,首先提取所有时间组成部分:

long oneYear = 60 * 24 * 365;
long oneDay = 60 * 24;
long oneHour = 60;

// extract years
int years = time / oneYear;
// update your time
time = time % oneYear;

// extract days
long days = time / oneDay;
// update your time
time = time % oneDay;

// extract hours
long hours = time / oneHour;

// extract minutes (the remaining)
minutes = time % oneHour;

然后,构建您的字符串:

StringBuilder sb = new StringBuilder( "Last time " );
if ( years != 0 ) {
sb.append( years ).append( "y " );
}
if ( days != 0 ) {
sb.append( days ).append( "d " );
}
if ( hours != 0 ) {
sb.append( hours ).append( "h " );
}
if ( minutes != 0 ) {
sb.append( minutes ).append( "m " );
}
sb.append( " ago" );

完整的方法是:

public String getLastgame() {

long time = ((System.currentTimeMillis() / 60000) - this.config.getLastgameTime());

long oneYear = 60 * 24 * 365;
long oneDay = 60 * 24;
long oneHour = 60;

// extract years
int years = time / oneYear;
// update your time
time = time % oneYear;

// extract days
long days = time / oneDay;
// update your time
time = time % oneDay;

// extract hours
long hours = time / oneHour;

// extract minutes (the remaining)
minutes = time % oneHour;

StringBuilder sb = new StringBuilder( "Last time " );
if ( years != 0 ) {
sb.append( years ).append( "y " );
}
if ( days != 0 ) {
sb.append( days ).append( "d " );
}
if ( hours != 0 ) {
sb.append( hours ).append( "h " );
}
if ( minutes != 0 ) {
sb.append( minutes ).append( "m " );
}
sb.append( " ago" );

return sb.toString();

}

关于java - 有没有办法将纳秒时间转换为不带零的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16751438/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com