将秒值转换为小时分钟秒?

我一直在尝试将一个秒值(在 BigDecimal 变量中)转换为一个编辑文本中的字符串,比如“1小时22分33秒”或类似的内容。

我试过了:

String sequenceCaptureTime = "";
BigDecimal roundThreeCalc = new BigDecimal("0");
BigDecimal hours = new BigDecimal("0");
BigDecimal myremainder = new BigDecimal("0");
BigDecimal minutes = new BigDecimal("0");
BigDecimal seconds = new BigDecimal("0");
BigDecimal var3600 = new BigDecimal("3600");
BigDecimal var60 = new BigDecimal("60");

(我有一个 round Three Calc,它是以秒为单位的值,所以我尝试在这里转换它。)

hours = (roundThreeCalc.divide(var3600));
myremainder = (roundThreeCalc.remainder(var3600));
minutes = (myremainder.divide(var60));
seconds = (myremainder.remainder(var60));
sequenceCaptureTime =  hours.toString() + minutes.toString() + seconds.toString();

然后,我将 edit Text 设置为 sequnceCaptureTime String。 但是没成功。每次都会强制关闭应用程序。我在这里完全不能胜任,非常感谢你的帮助。编程愉快!

293599 次浏览

你应该有更多的运气

hours = roundThreeCalc.divide(var3600, BigDecimal.ROUND_FLOOR);
myremainder = roundThreeCalc.remainder(var3600);
minutes = myremainder.divide(var60, BigDecimal.ROUND_FLOOR);
seconds = myremainder.remainder(var60);

这将在每次除法之后删除小数值。

编辑: 如果那不起作用,试试这个。(我只是编写和测试它)

public static int[] splitToComponentTimes(BigDecimal biggy)
{
long longVal = biggy.longValue();
int hours = (int) longVal / 3600;
int remainder = (int) longVal - hours * 3600;
int mins = remainder / 60;
remainder = remainder - mins * 60;
int secs = remainder;


int[] ints = {hours , mins , secs};
return ints;
}

有必要使用 BigDecimal 吗?如果没有必要,我会使用 int 或 long 表示秒,这样可以简化一些事情:

hours = totalSecs / 3600;
minutes = (totalSecs % 3600) / 60;
seconds = totalSecs % 60;


timeString = String.format("%02d:%02d:%02d", hours, minutes, seconds);

但是,您可能需要填充每个字符串,以确保它们是字符串中的两位数值(或其他值)。

下面是我解决这个问题的函数:

public static String getConvertedTime(double time){


double h,m,s,mil;


mil = time % 1000;
s = time/1000;
m = s/60;
h = m/60;
s = s % 60;
m = m % 60;
h = h % 24;


return ((int)h < 10 ? "0"+String.valueOf((int)h) : String.valueOf((int)h))+":"+((int)m < 10 ? "0"+String.valueOf((int)m) : String.valueOf((int)m))
+":"+((int)s < 10 ? "0"+String.valueOf((int)s) : String.valueOf((int)s))
+":"+((int)mil > 100 ? String.valueOf((int)mil) : (int)mil > 9 ? "0"+String.valueOf((int)mil) : "00"+String.valueOf((int)mil));
}

下面是工作代码:

private String getDurationString(int seconds) {


int hours = seconds / 3600;
int minutes = (seconds % 3600) / 60;
seconds = seconds % 60;


return twoDigitString(hours) + " : " + twoDigitString(minutes) + " : " + twoDigitString(seconds);
}


private String twoDigitString(int number) {


if (number == 0) {
return "00";
}


if (number / 10 == 0) {
return "0" + number;
}


return String.valueOf(number);
}

我用这个:

 public String SEG2HOR( long lnValue) {     //OK
String lcStr = "00:00:00";
String lcSign = (lnValue>=0 ? " " : "-");
lnValue = lnValue * (lnValue>=0 ? 1 : -1);


if (lnValue>0) {
long lnHor  = (lnValue/3600);
long lnHor1 = (lnValue % 3600);
long lnMin  = (lnHor1/60);
long lnSec  = (lnHor1 % 60);


lcStr = lcSign + ( lnHor < 10 ? "0": "") + String.valueOf(lnHor) +":"+
( lnMin < 10 ? "0": "") + String.valueOf(lnMin) +":"+
( lnSec < 10 ? "0": "") + String.valueOf(lnSec) ;
}


return lcStr;
}
private String ConvertSecondToHHMMString(int secondtTime)
{
TimeZone tz = TimeZone.getTimeZone("UTC");
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
df.setTimeZone(tz);
String time = df.format(new Date(secondtTime*1000L));


return time;


}

在 Java8中非常有用的东西

import java.time.LocalTime;


private String ConvertSecondToHHMMSSString(int nSecondTime) {
return LocalTime.MIN.plusSeconds(nSecondTime).toString();
}

DateUtils.formatElapsedTime(long)格式化“ MM:SS”或“ H:MM:SS”格式的运行时间。它返回您正在查找的 String。您可以找到文档 给你

如果你想让单位 hminsec持续一段时间,你可以使用这个:

public static String convertSeconds(int seconds) {
int h = seconds/ 3600;
int m = (seconds % 3600) / 60;
int s = seconds % 60;
String sh = (h > 0 ? String.valueOf(h) + " " + "h" : "");
String sm = (m < 10 && m > 0 && h > 0 ? "0" : "") + (m > 0 ? (h > 0 && s == 0 ? String.valueOf(m) : String.valueOf(m) + " " + "min") : "");
String ss = (s == 0 && (h > 0 || m > 0) ? "" : (s < 10 && (h > 0 || m > 0) ? "0" : "") + String.valueOf(s) + " " + "sec");
return sh + (h > 0 ? " " : "") + sm + (m > 0 ? " " : "") + ss;
}


int seconds = 3661;
String duration = convertSeconds(seconds);

有很多条件运算符,方法会返回这些字符串:

0    -> 0 sec
5    -> 5 sec
60   -> 1 min
65   -> 1 min 05 sec
3600 -> 1 h
3601 -> 1 h 01 sec
3660 -> 1 h 01
3661 -> 1 h 01 min 01 sec
108000 -> 30 h

这是我的简单解决方案:

String secToTime(int sec) {
int seconds = sec % 60;
int minutes = sec / 60;
if (minutes >= 60) {
int hours = minutes / 60;
minutes %= 60;
if( hours >= 24) {
int days = hours / 24;
return String.format("%d days %02d:%02d:%02d", days,hours%24, minutes, seconds);
}
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
return String.format("00:%02d:%02d", minutes, seconds);
}

Test Results :

Result: 00:00:36 - 36
Result: 01:00:07 - 3607
Result: 6313 days 12:39:05 - 545488745

我知道这很老套,但是在 java 8中:

LocalTime.MIN.plusSeconds(120).format(DateTimeFormatter.ISO_LOCAL_TIME)

我更喜欢 Java 的构建在 时间单位库中

long seconds = TimeUnit.MINUTES.toSeconds(8);

我在 python 中使用它来将表示秒的 float 转换为小时、分钟、秒和微秒。它相当优雅,并且可以方便地通过 strptime 转换为 datetime 类型。如果需要的话,它也可以很容易地延长到更长的间隔(几周、几个月等)。

    def sectohmsus(seconds):
x = seconds
hmsus = []
for i in [3600, 60, 1]:  # seconds in a hour, minute, and second
hmsus.append(int(x / i))
x %= i
hmsus.append(int(round(x * 1000000)))  # microseconds
return hmsus  # hours, minutes, seconds, microsecond

因此,我喜欢把事情简单化:

    int tot_seconds = 5000;
int hours = tot_seconds / 3600;
int minutes = (tot_seconds % 3600) / 60;
int seconds = tot_seconds % 60;


String timeString = String.format("%02d Hour %02d Minutes %02d Seconds ", hours, minutes, seconds);


System.out.println(timeString);

结果是: 01小时23分20秒

我已经尝试了最好的方法和更少的代码,但可能有点难以理解我是如何写我的代码,但如果你擅长数学,它是如此容易

import java.util.Scanner;

上课时间{

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double s;




System.out.println("how many second you have ");
s =input.nextInt();






double h=s/3600;
int h2=(int)h;


double h_h2=h-h2;
double m=h_h2*60;
int m1=(int)m;


double m_m1=m-m1;
double m_m1s=m_m1*60;












System.out.println(h2+" hours:"+m1+" Minutes:"+Math.round(m_m1s)+" seconds");










}

}

越过它就越精确!

使用 GregorianCalendar 做这件事的一个好的和简单的方法

将它们导入到项目中:

import java.util.GregorianCalendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Scanner;

然后:

Scanner s = new Scanner(System.in);


System.out.println("Seconds: ");
int secs = s.nextInt();


GregorianCalendar cal = new GregorianCalendar(0,0,0,0,0,secs);
Date dNow = cal.getTime();
SimpleDateFormat ft = new SimpleDateFormat("HH 'hours' mm 'minutes' ss 'seconds'");
System.out.println("Your time: " + ft.format(dNow));

这个代码运行良好:

txtTimer.setText(String.format("%02d:%02d:%02d",(SecondsCounter/3600), ((SecondsCounter % 3600)/60), (SecondsCounter % 60)));

只要几分钟,几秒钟,用这个

String.format("%02d:%02d", (seconds / 3600 * 60 + ((seconds % 3600) / 60)), (seconds % 60))

使用 Java8,您可以很容易地实现长时间的 String 格式的时间,比如,

LocalTime.ofSecondOfDay(86399L)

在这里,给定的值是最大允许转换(最多24小时) ,结果将是

23:59:59

优点: 1)不需要手动转换,并附加0为单位数字

缺点: 只工作24小时

从 java.time 的持续时间

    BigDecimal secondsValue = BigDecimal.valueOf(4953);
if (secondsValue.compareTo(BigDecimal.valueOf(Long.MAX_VALUE)) > 0) {
System.out.println("Seconds value " + secondsValue + " is out of range");
} else {
Duration dur = Duration.ofSeconds(secondsValue.longValueExact());
long hours = dur.toHours();
int minutes = dur.toMinutesPart();
int seconds = dur.toSecondsPart();


System.out.format("%d hours %d minutes %d seconds%n", hours, minutes, seconds);
}

这个代码片段的输出是:

1小时22分33秒

如果在 BigDecimal中有一个非零分数秒,这段代码就不会像现在这样工作,但是你可以修改它。该代码在 Java9及更高版本中可以工作。在 Java8中,从 Duration到小时和秒的转换比较冗长,请参阅底部的链接。我留给你选择正确的单数或复数形式的单词(一小时几个小时等)。

连结

虽然还有很多正确的答案和一个被接受的答案,如果你想要一个更加手工和系统化的方式来做这件事,我建议这样的东西:

/**
* Factors for converting seconds in minutes, minutes in hours, etc.
*/
private static int[] FACTORS = new int[] {
60, 60, 24, 7
};


/**
* Names of each time unit.
* The length of this array needs to be FACTORS.length + 1.
* The last one is the name of the remainder after
* obtaining each component.
*/
private static String[] NAMES = new String[] {
"second", "minute", "hour", "day", "week"
};


/**
* Checks if quantity is 1 in order to use or not the plural.
*/
private static String quantityToString(int quantity, String name) {
if (quantity == 1) {
return String.format("%d %s", quantity, name);
}
return String.format("%d %ss", quantity, name);
}


/**
* The seconds to String method.
*/
private static String secondsToString(int seconds) {
List<String> components = new ArrayList<>();


/**
* Obtains each component and stores only if is not 0.
*/
for (int i = 0; i < FACTORS.length; i++) {
int component = seconds % FACTORS[i];
seconds /= FACTORS[i];
if (component != 0) {
components.add(quantityToString(component, NAMES[i]));
}
}
    

/**
* The remainder is the last component.
*/
if (seconds != 0) {
components.add(quantityToString(seconds, NAMES[FACTORS.length]));
}
    

/**
* We have the non-0 components in reversed order.
* This could be extracted to another method.
*/
StringBuilder builder = new StringBuilder();
for (int i = components.size() - 1; i >= 0; i--) {
if (i == 0 && components.size() > 1) {
builder.append(" and ");
} else if (builder.length() > 0) {
builder.append(", ");
}
builder.append(components.get(i));
}
    

return builder.toString();
}

结果如下:

System.out.println(secondsToString(5_000_000)); // 8 weeks, 1 day, 20 hours, 53 minutes and 20 seconds
System.out.println(secondsToString(500_000)); // 5 days, 18 hours, 53 minutes and 20 seconds
System.out.println(secondsToString(60*60*24)); // 1 day
System.out.println(secondsToString(2*60*60*24 + 3*60)); // 2 days and 3 minutes
System.out.println(secondsToString(60*60*24 + 3 * 60 * 60 + 53)); // 1 day, 3 hours and 53 seconds