Konwertuj sekundy na dni, minuty i godziny w Obj-c

W objective-c, Jak mogę przekonwertować liczbę całkowitą (reprezentującą sekundy) na dni, minuty, godziny?

Dzięki!

Author: higginbotham, 2009-02-21

11 answers

W tym przypadku wystarczy podzielić.

days = num_seconds / (60 * 60 * 24);
num_seconds -= days * (60 * 60 * 24);
hours = num_seconds / (60 * 60);
num_seconds -= hours * (60 * 60);
minutes = num_seconds / 60;

Dla bardziej wyrafinowanych obliczeń daty, takich jak liczba dni w ciągu dziesięciu milionów sekund po godzinie 15: 00 19 stycznia 1983 roku, można użyć klasy NSCalendar wraz z NSDateComponents. Pomaga tutaj Przewodnik Apple date and time programming guide.

 43
Author: fish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-02-21 03:57:25

Spróbuj tego,

int forHours = seconds / 3600, 
remainder = seconds % 3600, 
forMinutes = remainder / 60, 
forSeconds = remainder % 60;

I możesz go użyć, aby uzyskać więcej szczegółów w dniach, tygodniach, miesiącach i latach, postępując zgodnie z tą samą procedurą

 33
Author: Amr Faisal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-11-05 19:58:44

Wiem, że to stary post, ale i tak chciałem się nim podzielić. Poniższy kod jest tym, czego używam.

int seconds = (totalSeconds % 60);
int minutes = (totalSeconds % 3600) / 60;
int hours = (totalSeconds % 86400) / 3600;
int days = (totalSeconds % (86400 * 30)) / 86400;

Pierwsza linia - otrzymujemy resztę sekund dzieląc przez liczbę sekund w minutach.

Druga linia-otrzymujemy resztę sekund po podzieleniu przez liczbę sekund w ciągu godziny. Następnie dzielimy to przez sekundy w minutę.

Trzecia linia-otrzymujemy resztę sekund po podzieleniu przez liczbę sekund w ciągu dnia. Następnie dzielimy to przez liczba sekund w godzinę.

Czwarta linia-otrzymujemy pozostałą część sekundy po podzieleniu przez liczbę sekund w miesiącu. Następnie dzielimy to przez liczbę sekund w ciągu dnia. Przydałoby się kilka dni...

int days = totalSeconds / 86400;

Ale gdybyśmy użyli powyższej linii i chcieli kontynuować i dostać miesiące, skończylibyśmy z 1 miesiącem i 30 dni, kiedy chcieliśmy dostać tylko 1 miesiąc.

Otwórz plac zabaw w Xcode i wypróbuj go.
 9
Author: Sean Marraffa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-06 07:39:14

Najbardziej preferowanym sposobem w objective-c może być ten, jak zaleca Apple w swoim dokumencie.

  NSDate *startDate = [NSDate date];
    NSDate *endDate = [NSDate dateWithTimeInterval:(365*24*60*60*3+24*60*60*129) sinceDate:startDate];

    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];

    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSDateComponents *components = [gregorian components:unitFlags
                                                fromDate:startDate
                                                  toDate:endDate options:0];
    NSInteger years = [components year];
    NSInteger months = [components month];
    NSInteger days = [components day]; 
    NSLog(@"years = %ld months = %ld days = %ld",years,months,days);

Upewnij się, że nie pobierasz komponentów Nie zdefiniowanych za pomocą unitFlags, liczba całkowita będzie "undefined".

 6
Author: JeanNicolas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-08 17:45:27

Użyj wbudowanej funkcji strftime ():

static char timestr[80];
char * HHMMSS ( time_t secs )
{
    struct tm ts;
    ts = *localtime(&secs);
    strftime(timestr, sizeof(timestr), "%a %b %d %H:%M:%S %Y %Z", &ts); // "Mon May 1, 2012 hh:mm:ss zzz"
    return timestr;
}
 3
Author: Craig Detrick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-16 06:37:03

Tylko modyfikacja bitów dla obu kompatybilnych z 32 bitami i 64 bitami. Za pomocą NSInteger system automatycznie konwertuje do int lub long na podstawie 32/64 bitów.

NSInteger seconds = 10000;
NSInteger remainder = seconds % 3600;
NSInteger hours = seconds / 3600;
NSInteger minutes = remainder / 60;
NSInteger forSeconds = remainder % 60;

W ten sam sposób można konwertować na dni, tygodnie, miesiące, lata

 2
Author: Tai Le Anh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-06 08:20:44

To jest mój algorytm konwersji sekund na sekundy, minuty i godziny (używając tylko całkowitej liczby sekund i relacji między każdą z nich):

int S = totalSeconds % BaseSMH

int M = ((totalSeconds - totalSeconds % BaseSMH) % BaseSMH ^ 2) / BaseSMH

int H = (totalSeconds - totalSeconds % BaseSMH - ((totalSeconds - totalSeconds % BaseSMH) % BaseSMH ^ 2)) / BaseSMH ^ 2

I oto moje wyjaśnienie:

Czas testu zamieniony na sekundy: HH:MM: SS = 02: 20: 10 => totalSeconds = 2 * 3600 + 20 * 60 + 10 = 7200 + 1200 + 10 = 8410

Baza pomiędzy sekundami - > minutami i minutami - > godzinami wynosi 60 (od sekund -> godzin wynosi 60 ^ 2 = 3600).

int totalSeconds = 8410
const int BaseSMH = 60

Każda jednostka (tutaj reprezentowany przez zmienną) można obliczyć, usuwając poprzednią jednostkę (wyrażoną w sekundach) z całkowitej liczby sekund i podzielić ją przez jej stosunek między sekundami a jednostką, którą próbujemy obliczyć. Tak wygląda każda kalulacja za pomocą tego algorytmu:

int S = totalSeconds % BaseSMH

int M = ((totalSeconds - S) % BaseSMH ^ 2) / BaseSMH

int H = (totalSeconds - S - M * BaseSMH) / BaseSMH ^ 2

Tak jak w przypadku całej matematyki możemy teraz zastąpić każdą jednostkę w obliczeniach minut i godzin tym, jak obliczyliśmy poprzednią jednostkę i każde obliczenie będzie wyglądać tak (pamiętaj, że dzielenie z BaseSMH w obliczeniach M i mnożenie przez BaseSMH w kalulacji H eliminuje się wzajemnie):

int S = totalSeconds % BaseSMH

int M = ((totalSeconds - totalSeconds % BaseSMH) % BaseSMH ^ 2) / BaseSMH

int H = (totalSeconds - totalSeconds % BaseSMH - ((totalSeconds - totalSeconds % BaseSMH) % BaseSMH ^ 2)) / BaseSMH ^ 2

Testowanie z "totalSeconds " i" BaseSMH " z góry będzie wyglądało tak:

int S = 8410 % 60

int M = ((8410 - 8410 % 60) % 60 ^ 2) / 60

int H = (8410 - 8410 % 60 - ((8410 - 8410 % 60) % 60 ^ 2)) / 60 ^ 2

Obliczanie S:

int S = 8410 % 60 = 10

Obliczanie M:

int M = ((8410 - 8410 % 60) % 60 ^ 2) / 60 
= ((8410 - 10) % 3600) / 60 
= (8400 % 3600) / 60 
= 1200 / 60 
= 20

Obliczanie H:

int H = (8410 - 8410 % 60 - ((8410 - 8410 % 60) % 60 ^ 2)) / 60 ^ 2 
= (8410 - 10 - ((8410 - 10) % 3600)) / 3600
= (8400 - (8400 % 3600)) / 3600
= (8400 - 1200) / 3600
= 7200 / 3600
= 2

Dzięki temu możesz dodać dowolną jednostkę, wystarczy obliczyć, jaka jest relacja między sekundami a jednostką, którą chcesz. Mam nadzieję, że rozumiesz moje wyjaśnienia każdego kroku. Jeśli nie, po prostu zapytaj i mogę wyjaśnić dalej.

 1
Author: Tor Ymer Nordström,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-19 06:42:05
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
    Date dateObj1=null;
    Date dateObj2=null;
    try {
        // String format = "MM/dd/yyyy hh:mm:ss";
        dateObj1 = sdf.parse(Appconstant.One_One_time);
        dateObj2 = sdf.parse(Appconstant.One_Two_time);
        Log.e(TAG, "dateObj12" + dateObj1.toString() + "---" + dateObj2.toString());
        DecimalFormat crunchifyFormatter = new DecimalFormat("###,###");
        long diff = dateObj2.getTime() - dateObj1.getTime();
        /*int diffDays = (int) (diff / (24 * 60 * 60 * 1000));
        System.out.println("difference between days: " + diffDays);
        int diffhours = (int) (diff / (60 * 60 * 1000));
        System.out.println("difference between hours: "
                + crunchifyFormatter.format(diffhours));
        int diffmin = (int) (diff / (60 * 1000));
        System.out.println("difference between minutes: "
                + crunchifyFormatter.format(diffmin));*/
        int diffsec = (int) (diff / (1000));
        System.out.println("difference between seconds:"
                + crunchifyFormatter.format(diffsec));
 0
Author: Vela,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-06 07:48:33

Otrzymasz dni, godziny,minuty i sekundy z całkowitych sekund (self.secondsLeft)

days = self.secondsLeft/86400;
hours = (self.secondsLeft %86400)/3600;
minutes = (self.secondsLeft % 3600) / 60;
seconds = (self.secondsLeft %3600) % 60;

Kod ......

  [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];

-(void) updateCountdown {

    int days,hours,minutes,seconds;
    self.secondsLeft--;

    days = self.secondsLeft/86400;
    hours = (self.secondsLeft %86400)/3600;
    minutes = (self.secondsLeft % 3600) / 60;
    seconds = (self.secondsLeft %3600) % 60;

    NSLog(@"Time Remaining =%@",[NSString stringWithFormat:@"%02d:%02d:%02d:%02d",days, hours, minutes,seconds]);
}
 0
Author: Deepak Nair,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-05 06:55:59

Początkowo wypracowałem rozwiązanie podobne do odpowiedzi fish ' a:

const secondsToString = s => {
  const secondsOfYear = 60 * 60 * 24 * 365;
  const secondsOfDay = 60 * 60 * 24;
  const secondsOfHour = 60 * 60;
  const secondsOfMinute = 60;

  let y = ~~(s / secondsOfYear);    s %= secondsOfYear;
  let d = ~~(s / secondsOfDay);     s %= secondsOfDay;
  let h = ~~(s / secondsOfHour);    s %= secondsOfHour;
  let m = ~~(s / secondsOfMinute);  s %= secondsOfMinute;

  y = (y > 0 ? (y + 'y ') : '');
  d = (d > 0 ? (d + 'd ') : '');
  h = (h > 0 ? (h + 'h ') : '');
  m = (m > 0 ? (m + 'm ') : '');
  s = (s > 0 ? (s + 's ') : '');

  return y + d + h + m + s;
}

Zauważyłem, że można go uogólnić za pomocą funkcji array map() i reduce(), ponieważ zawiera pewne iteracje i rekursje.

const intervalToLevels = (interval, levels) => {
  const cbFun = (d, c) => {
    let bb = d[1] % c[0],
      aa = (d[1] - bb) / c[0];
    aa = aa > 0 ? aa + c[1] : '';

    return [d[0] + aa, bb];
  };

  let rslt = levels.scale.map((d, i, a) => a.slice(i).reduce((d, c) => d * c))
    .map((d, i) => ([d, levels.units[i]]))
    .reduce(cbFun, ['', interval]);
  return rslt[0];
};

const TimeLevels = {
  scale: [365, 24, 60, 60, 1],
  units: ['y ', 'd ', 'h ', 'm ', 's ']
};
const secondsToString = interval => intervalToLevels(interval, TimeLevels);

Łatwo można rozszerzyć funkcję intervalToLevels() na inne poziomy pomiaru, takie jak masa cieczy, długość i tak dalej.

const LengthLevels = {
  scale: [1760, 3, 12, 1],
  units: ['mi ', 'yd ', 'ft ', 'in ']
};
const inchesToString = interval => intervalToLevels(interval, LengthLevels);

const LiquidsLevels = {
  scale: [4, 2, 2, 8, 1],
  units: ['gal ', 'qt ', 'pt ', 'cup ', 'fl_oz ']
};
const ouncesToString = interval => intervalToLevels(interval, LiquidsLevels);
 0
Author: timothyzhang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-09 01:41:02

Spróbuj wykonać następujące czynności:

    x=int(input("enter a positive integer: "))
    sec = int(x % 60);
    minu =int((x % 3600) / 60);
    ho =int((x % 86400) / 3600);
    days =int(x / (60 * 60 * 24));
    print(int(days),"days", ho,"hours", minu , "minutes" , sec ,"seconds" )
 -1
Author: aridj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-03 04:38:52