programing

초 값을 시간 분 초로 변환 하시겠습니까?

nasanasas 2020. 9. 6. 10:06
반응형

초 값을 시간 분 초로 변환 하시겠습니까?


나는 초 값 (BigDecimal 변수)을 "1 시간 22 분 33 초"와 같은 editText의 문자열로 변환하려고했습니다.

나는 이것을 시도했다 :

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");

(초 단위의 값인 roundThreeCalc가 있으므로 여기서 변환하려고합니다.)

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

그런 다음 editText를 sequnceCaptureTime String으로 설정합니다. 그러나 그것은 작동하지 않았습니다. 매번 앱을 강제 종료합니다. 나는 여기에 완전히 깊이 빠져 있습니다. 어떤 도움이라도 대단히 감사합니다. 즐거운 코딩 되세요!


당신은 더 많은 행운을 가져야합니다

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);

하지만 문자열에서 두 자리 값 (또는 기타)인지 확인하기 위해 각각을 채울 수 있습니다.


DateUtils.formatElapsedTime(long), " MM:SS"또는 " H:MM:SS" 형식으로 경과 시간을 형식화합니다 . 찾고있는 문자열을 반환합니다. 여기 에서 설명서를 찾을 수 있습니다.


다음은 작동 코드입니다.

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);
}

Java 8에서 정말 유용한 것

import java.time.LocalTime;

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

Java의 내장 TimeUnit 라이브러리를 선호 합니다.

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

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;

}

이것은 내 간단한 해결책입니다.

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

따라서 나는 일을 단순하게 유지하고 싶습니다.

    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 초


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)));

나는 이것을 사용한다 :

 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;           
    }

문제를 해결하는 기능은 다음과 같습니다.

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));
}

당신이 단위를 원하는 경우 h, minsec기간에 대한이를 사용할 수 있습니다 :

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);

That's a lot of conditional operators. The method will return those strings:

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

I know this is pretty old but in java 8:

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

for just minutes and seconds use this

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

I use this in python to convert a float representing seconds to hours, minutes, seconds, and microseconds. It's reasonably elegant and is handy for converting to a datetime type via strptime to convert. It could also be easily extended to longer intervals (weeks, months, etc.) if needed.

    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

i have tried the best way and less code but may be it is little bit difficult to understand how i wrote my code but if you good at maths it is so easy

import java.util.Scanner;

class hours {

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");





}

}

more over it is accurate !


With Java 8, you can easily achieve time in String format from long seconds like,

LocalTime.ofSecondOfDay(86399L)

Here, given value is max allowed to convert (upto 24 hours) and result will be

23:59:59

Pros : 1) No need to convert manually and to append 0 for single digit

Cons : work only for up to 24 hours


With Java 8, you can easily achieve time in LocalTime format from long seconds like,

LocalTime.ofSecondOfDay(86399L)

Here, given value is max allowed to convert (upto 24 hours) and result will be

23:59:59

Pros : 1) No need to convert manually and to append 0 for single digit

Cons : work only for up to 24 hours

참고URL : https://stackoverflow.com/questions/6118922/convert-seconds-value-to-hours-minutes-seconds

반응형