Java/Kotlin/Android - format time (hh:mm:ss) and remove unnecessary zeros from the beginningHow do you format date and time in Android?How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?How to format a Java string with leading zero?Removing whitespace from strings in JavaT-SQL Format seconds as HH:MM:SS time24 Hour CountDown Timer with three separate textviews for hours, minutes, secondJava How to get just HH:mm:ss from Dateandroid java String.format padding zeroes before and after decimal on a doubleHow to format duration string like PT3M33S to HH:mm:ssAndroid kotlin string formats in different orders

How to make a villain when your PCs are villains?

At what temperature should the earth be cooked to prevent human infection?

What is the color associated with lukewarm?

Fill the maze with a wall-following Snake until it gets stuck

Using roof rails to set up hammock

How to ask if I can mow my neighbor's lawn

What kind of chart is this?

Boss making me feel guilty for leaving the company at the end of my internship

How "fast" does astronomical events happen?

Converting 3x7 to a 1x7. Is it possible with only existing parts?

Huge Heap Table and table compression on SQL Server 2016

Is swap gate equivalent to just exchanging the wire of the two qubits?

Basic power tool set for Home repair and simple projects

How to make all magic-casting innate, but still rare?

...and then she held the gun

Can I drive in EU states and Switzerland with German proof of a surrendered U.S. license?

First occurrence in the Sixers sequence

Is this set open or closed (or both?)

Leveraging cash for buying car

How did Avada Kedavra get its name?

Is there a term for someone whose preferred policies are a mix of Left and Right?

Is there any effect in D&D 5e that cannot be undone?

How to write a nice frame challenge?

How to avoid offending original culture when making conculture inspired from original



Java/Kotlin/Android - format time (hh:mm:ss) and remove unnecessary zeros from the beginning


How do you format date and time in Android?How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?How to format a Java string with leading zero?Removing whitespace from strings in JavaT-SQL Format seconds as HH:MM:SS time24 Hour CountDown Timer with three separate textviews for hours, minutes, secondJava How to get just HH:mm:ss from Dateandroid java String.format padding zeroes before and after decimal on a doubleHow to format duration string like PT3M33S to HH:mm:ssAndroid kotlin string formats in different orders






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








-1















My application displays time left in such format hh:mm:ss, for example, 01:05:45 what stands for one hour 5 minutes and 45 seconds.



When hours or minutes are zero I would like not to display them. Currently, if 45 seconds are remaining my timer will show '00:00:45'. The expected result is just '45'.



I need some kind of Java/Kotlin/Android method to produce the following outputs:



  • 1 hour 13 minutes and 10 seconds ==> 01:13:10

  • 0 hours 13 minutes and 10 seconds ==> 13:10

  • 3 hours 0 minutes and 16 seconds ==> 03:00:16

  • 0 hour 0 minutes and 5 seconds ==> 5

Currently I use such string as a formatter:



<string name="time_default_formatter" translatable="false">%02d:%02d:%02d</string>


I tried to manually replace string "00:" with "" but it fails when it comes to a 3rd example. Also, I think standard formatting should provide something like that but I keep failing to find it.



Edit: I can do it in code. The thing is I am looking for an elegant solution.










share|improve this question
























  • Is this a hard requirement? Most electronic timers and timer apps do include at least the minutes, even if zero.

    – chrylis
    Mar 7 at 16:07











  • It is a hard requirement I'm afraid. The client saw such a solution in a few timer apps and he wants the same thing.

    – Michał Powłoka
    Mar 7 at 16:08












  • In that case you're probably going to need conditional logic to select from different formats or concatenate only the relevant fields.

    – chrylis
    Mar 7 at 16:09











  • I will do so if I must. Yet I hope there is a more elegant solution.

    – Michał Powłoka
    Mar 7 at 16:10











  • So you need a formatting pattern or code?

    – forpas
    Mar 7 at 16:10

















-1















My application displays time left in such format hh:mm:ss, for example, 01:05:45 what stands for one hour 5 minutes and 45 seconds.



When hours or minutes are zero I would like not to display them. Currently, if 45 seconds are remaining my timer will show '00:00:45'. The expected result is just '45'.



I need some kind of Java/Kotlin/Android method to produce the following outputs:



  • 1 hour 13 minutes and 10 seconds ==> 01:13:10

  • 0 hours 13 minutes and 10 seconds ==> 13:10

  • 3 hours 0 minutes and 16 seconds ==> 03:00:16

  • 0 hour 0 minutes and 5 seconds ==> 5

Currently I use such string as a formatter:



<string name="time_default_formatter" translatable="false">%02d:%02d:%02d</string>


I tried to manually replace string "00:" with "" but it fails when it comes to a 3rd example. Also, I think standard formatting should provide something like that but I keep failing to find it.



Edit: I can do it in code. The thing is I am looking for an elegant solution.










share|improve this question
























  • Is this a hard requirement? Most electronic timers and timer apps do include at least the minutes, even if zero.

    – chrylis
    Mar 7 at 16:07











  • It is a hard requirement I'm afraid. The client saw such a solution in a few timer apps and he wants the same thing.

    – Michał Powłoka
    Mar 7 at 16:08












  • In that case you're probably going to need conditional logic to select from different formats or concatenate only the relevant fields.

    – chrylis
    Mar 7 at 16:09











  • I will do so if I must. Yet I hope there is a more elegant solution.

    – Michał Powłoka
    Mar 7 at 16:10











  • So you need a formatting pattern or code?

    – forpas
    Mar 7 at 16:10













-1












-1








-1








My application displays time left in such format hh:mm:ss, for example, 01:05:45 what stands for one hour 5 minutes and 45 seconds.



When hours or minutes are zero I would like not to display them. Currently, if 45 seconds are remaining my timer will show '00:00:45'. The expected result is just '45'.



I need some kind of Java/Kotlin/Android method to produce the following outputs:



  • 1 hour 13 minutes and 10 seconds ==> 01:13:10

  • 0 hours 13 minutes and 10 seconds ==> 13:10

  • 3 hours 0 minutes and 16 seconds ==> 03:00:16

  • 0 hour 0 minutes and 5 seconds ==> 5

Currently I use such string as a formatter:



<string name="time_default_formatter" translatable="false">%02d:%02d:%02d</string>


I tried to manually replace string "00:" with "" but it fails when it comes to a 3rd example. Also, I think standard formatting should provide something like that but I keep failing to find it.



Edit: I can do it in code. The thing is I am looking for an elegant solution.










share|improve this question
















My application displays time left in such format hh:mm:ss, for example, 01:05:45 what stands for one hour 5 minutes and 45 seconds.



When hours or minutes are zero I would like not to display them. Currently, if 45 seconds are remaining my timer will show '00:00:45'. The expected result is just '45'.



I need some kind of Java/Kotlin/Android method to produce the following outputs:



  • 1 hour 13 minutes and 10 seconds ==> 01:13:10

  • 0 hours 13 minutes and 10 seconds ==> 13:10

  • 3 hours 0 minutes and 16 seconds ==> 03:00:16

  • 0 hour 0 minutes and 5 seconds ==> 5

Currently I use such string as a formatter:



<string name="time_default_formatter" translatable="false">%02d:%02d:%02d</string>


I tried to manually replace string "00:" with "" but it fails when it comes to a 3rd example. Also, I think standard formatting should provide something like that but I keep failing to find it.



Edit: I can do it in code. The thing is I am looking for an elegant solution.







java android kotlin format string-formatting






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 25 at 3:29









Cœur

20.5k10119162




20.5k10119162










asked Mar 7 at 16:05









Michał PowłokaMichał Powłoka

326214




326214












  • Is this a hard requirement? Most electronic timers and timer apps do include at least the minutes, even if zero.

    – chrylis
    Mar 7 at 16:07











  • It is a hard requirement I'm afraid. The client saw such a solution in a few timer apps and he wants the same thing.

    – Michał Powłoka
    Mar 7 at 16:08












  • In that case you're probably going to need conditional logic to select from different formats or concatenate only the relevant fields.

    – chrylis
    Mar 7 at 16:09











  • I will do so if I must. Yet I hope there is a more elegant solution.

    – Michał Powłoka
    Mar 7 at 16:10











  • So you need a formatting pattern or code?

    – forpas
    Mar 7 at 16:10

















  • Is this a hard requirement? Most electronic timers and timer apps do include at least the minutes, even if zero.

    – chrylis
    Mar 7 at 16:07











  • It is a hard requirement I'm afraid. The client saw such a solution in a few timer apps and he wants the same thing.

    – Michał Powłoka
    Mar 7 at 16:08












  • In that case you're probably going to need conditional logic to select from different formats or concatenate only the relevant fields.

    – chrylis
    Mar 7 at 16:09











  • I will do so if I must. Yet I hope there is a more elegant solution.

    – Michał Powłoka
    Mar 7 at 16:10











  • So you need a formatting pattern or code?

    – forpas
    Mar 7 at 16:10
















Is this a hard requirement? Most electronic timers and timer apps do include at least the minutes, even if zero.

– chrylis
Mar 7 at 16:07





Is this a hard requirement? Most electronic timers and timer apps do include at least the minutes, even if zero.

– chrylis
Mar 7 at 16:07













It is a hard requirement I'm afraid. The client saw such a solution in a few timer apps and he wants the same thing.

– Michał Powłoka
Mar 7 at 16:08






It is a hard requirement I'm afraid. The client saw such a solution in a few timer apps and he wants the same thing.

– Michał Powłoka
Mar 7 at 16:08














In that case you're probably going to need conditional logic to select from different formats or concatenate only the relevant fields.

– chrylis
Mar 7 at 16:09





In that case you're probably going to need conditional logic to select from different formats or concatenate only the relevant fields.

– chrylis
Mar 7 at 16:09













I will do so if I must. Yet I hope there is a more elegant solution.

– Michał Powłoka
Mar 7 at 16:10





I will do so if I must. Yet I hope there is a more elegant solution.

– Michał Powłoka
Mar 7 at 16:10













So you need a formatting pattern or code?

– forpas
Mar 7 at 16:10





So you need a formatting pattern or code?

– forpas
Mar 7 at 16:10












2 Answers
2






active

oldest

votes


















1














String resources are meant for displaying actual text in a way that is easily localizable. They aren't meant for formatting dates and times; that's what DateUtils is for.




This class contains various date-related utilities for creating text
for things like elapsed time and date ranges, strings for days of the
week and months, and AM/PM text etc.




Which comes with a convenient formatElapsedTime() method; which formats a duration as you would expect.




Formats an elapsed time in the form "MM:SS" or "H:MM:SS"…




Unfortunately the last format you mentioned (which only displays seconds) is fairly uncommon, therefore unsupported by DateUtils. Though this can be easily remedied with the following function.



fun formatDuration(seconds: Long): String = if (seconds < 60) 
seconds.toString()
else
DateUtils.formatElapsedTime(seconds)






share|improve this answer























  • Works like a dream. That's exactly what I was looking for :)

    – Michał Powłoka
    Mar 8 at 10:09


















0














So far I haven't found any elegant in my opinion solution and I do it like that.



I have three formatting strings, one for each situation:



<string name="time_hours_minutes_seconds_formatter" translatable="false">%02d:%02d:%02d</string>
<string name="time_minutes_seconds_formatter" translatable="false">%02d:%02d</string>
<string name="time_seconds_formatter" translatable="false">%02d</string>


Then, manually I format it using function (in Kotlin):



 private fun formatTime(millis: Long): String 
val hours = TimeUnit.MILLISECONDS.toHours(millis) % 24
val minutes = TimeUnit.MILLISECONDS.toMinutes(millis) % 60
val seconds = TimeUnit.MILLISECONDS.toSeconds(millis) % 60

return when
hours == 0L && minutes == 0L -> String.format(
resources.getString(R.string.time_seconds_formatter), seconds
)

hours == 0L && minutes > 0L -> String.format(
resources.getString(R.string.time_minutes_seconds_formatter), minutes, seconds
)

else -> resources.getString(R.string.time_hours_minutes_seconds_formatter, hours, minutes, seconds)







share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55048137%2fjava-kotlin-android-format-time-hhmmss-and-remove-unnecessary-zeros-from-t%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    String resources are meant for displaying actual text in a way that is easily localizable. They aren't meant for formatting dates and times; that's what DateUtils is for.




    This class contains various date-related utilities for creating text
    for things like elapsed time and date ranges, strings for days of the
    week and months, and AM/PM text etc.




    Which comes with a convenient formatElapsedTime() method; which formats a duration as you would expect.




    Formats an elapsed time in the form "MM:SS" or "H:MM:SS"…




    Unfortunately the last format you mentioned (which only displays seconds) is fairly uncommon, therefore unsupported by DateUtils. Though this can be easily remedied with the following function.



    fun formatDuration(seconds: Long): String = if (seconds < 60) 
    seconds.toString()
    else
    DateUtils.formatElapsedTime(seconds)






    share|improve this answer























    • Works like a dream. That's exactly what I was looking for :)

      – Michał Powłoka
      Mar 8 at 10:09















    1














    String resources are meant for displaying actual text in a way that is easily localizable. They aren't meant for formatting dates and times; that's what DateUtils is for.




    This class contains various date-related utilities for creating text
    for things like elapsed time and date ranges, strings for days of the
    week and months, and AM/PM text etc.




    Which comes with a convenient formatElapsedTime() method; which formats a duration as you would expect.




    Formats an elapsed time in the form "MM:SS" or "H:MM:SS"…




    Unfortunately the last format you mentioned (which only displays seconds) is fairly uncommon, therefore unsupported by DateUtils. Though this can be easily remedied with the following function.



    fun formatDuration(seconds: Long): String = if (seconds < 60) 
    seconds.toString()
    else
    DateUtils.formatElapsedTime(seconds)






    share|improve this answer























    • Works like a dream. That's exactly what I was looking for :)

      – Michał Powłoka
      Mar 8 at 10:09













    1












    1








    1







    String resources are meant for displaying actual text in a way that is easily localizable. They aren't meant for formatting dates and times; that's what DateUtils is for.




    This class contains various date-related utilities for creating text
    for things like elapsed time and date ranges, strings for days of the
    week and months, and AM/PM text etc.




    Which comes with a convenient formatElapsedTime() method; which formats a duration as you would expect.




    Formats an elapsed time in the form "MM:SS" or "H:MM:SS"…




    Unfortunately the last format you mentioned (which only displays seconds) is fairly uncommon, therefore unsupported by DateUtils. Though this can be easily remedied with the following function.



    fun formatDuration(seconds: Long): String = if (seconds < 60) 
    seconds.toString()
    else
    DateUtils.formatElapsedTime(seconds)






    share|improve this answer













    String resources are meant for displaying actual text in a way that is easily localizable. They aren't meant for formatting dates and times; that's what DateUtils is for.




    This class contains various date-related utilities for creating text
    for things like elapsed time and date ranges, strings for days of the
    week and months, and AM/PM text etc.




    Which comes with a convenient formatElapsedTime() method; which formats a duration as you would expect.




    Formats an elapsed time in the form "MM:SS" or "H:MM:SS"…




    Unfortunately the last format you mentioned (which only displays seconds) is fairly uncommon, therefore unsupported by DateUtils. Though this can be easily remedied with the following function.



    fun formatDuration(seconds: Long): String = if (seconds < 60) 
    seconds.toString()
    else
    DateUtils.formatElapsedTime(seconds)







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 7 at 17:20









    BryanBryan

    8,31064588




    8,31064588












    • Works like a dream. That's exactly what I was looking for :)

      – Michał Powłoka
      Mar 8 at 10:09

















    • Works like a dream. That's exactly what I was looking for :)

      – Michał Powłoka
      Mar 8 at 10:09
















    Works like a dream. That's exactly what I was looking for :)

    – Michał Powłoka
    Mar 8 at 10:09





    Works like a dream. That's exactly what I was looking for :)

    – Michał Powłoka
    Mar 8 at 10:09













    0














    So far I haven't found any elegant in my opinion solution and I do it like that.



    I have three formatting strings, one for each situation:



    <string name="time_hours_minutes_seconds_formatter" translatable="false">%02d:%02d:%02d</string>
    <string name="time_minutes_seconds_formatter" translatable="false">%02d:%02d</string>
    <string name="time_seconds_formatter" translatable="false">%02d</string>


    Then, manually I format it using function (in Kotlin):



     private fun formatTime(millis: Long): String 
    val hours = TimeUnit.MILLISECONDS.toHours(millis) % 24
    val minutes = TimeUnit.MILLISECONDS.toMinutes(millis) % 60
    val seconds = TimeUnit.MILLISECONDS.toSeconds(millis) % 60

    return when
    hours == 0L && minutes == 0L -> String.format(
    resources.getString(R.string.time_seconds_formatter), seconds
    )

    hours == 0L && minutes > 0L -> String.format(
    resources.getString(R.string.time_minutes_seconds_formatter), minutes, seconds
    )

    else -> resources.getString(R.string.time_hours_minutes_seconds_formatter, hours, minutes, seconds)







    share|improve this answer



























      0














      So far I haven't found any elegant in my opinion solution and I do it like that.



      I have three formatting strings, one for each situation:



      <string name="time_hours_minutes_seconds_formatter" translatable="false">%02d:%02d:%02d</string>
      <string name="time_minutes_seconds_formatter" translatable="false">%02d:%02d</string>
      <string name="time_seconds_formatter" translatable="false">%02d</string>


      Then, manually I format it using function (in Kotlin):



       private fun formatTime(millis: Long): String 
      val hours = TimeUnit.MILLISECONDS.toHours(millis) % 24
      val minutes = TimeUnit.MILLISECONDS.toMinutes(millis) % 60
      val seconds = TimeUnit.MILLISECONDS.toSeconds(millis) % 60

      return when
      hours == 0L && minutes == 0L -> String.format(
      resources.getString(R.string.time_seconds_formatter), seconds
      )

      hours == 0L && minutes > 0L -> String.format(
      resources.getString(R.string.time_minutes_seconds_formatter), minutes, seconds
      )

      else -> resources.getString(R.string.time_hours_minutes_seconds_formatter, hours, minutes, seconds)







      share|improve this answer

























        0












        0








        0







        So far I haven't found any elegant in my opinion solution and I do it like that.



        I have three formatting strings, one for each situation:



        <string name="time_hours_minutes_seconds_formatter" translatable="false">%02d:%02d:%02d</string>
        <string name="time_minutes_seconds_formatter" translatable="false">%02d:%02d</string>
        <string name="time_seconds_formatter" translatable="false">%02d</string>


        Then, manually I format it using function (in Kotlin):



         private fun formatTime(millis: Long): String 
        val hours = TimeUnit.MILLISECONDS.toHours(millis) % 24
        val minutes = TimeUnit.MILLISECONDS.toMinutes(millis) % 60
        val seconds = TimeUnit.MILLISECONDS.toSeconds(millis) % 60

        return when
        hours == 0L && minutes == 0L -> String.format(
        resources.getString(R.string.time_seconds_formatter), seconds
        )

        hours == 0L && minutes > 0L -> String.format(
        resources.getString(R.string.time_minutes_seconds_formatter), minutes, seconds
        )

        else -> resources.getString(R.string.time_hours_minutes_seconds_formatter, hours, minutes, seconds)







        share|improve this answer













        So far I haven't found any elegant in my opinion solution and I do it like that.



        I have three formatting strings, one for each situation:



        <string name="time_hours_minutes_seconds_formatter" translatable="false">%02d:%02d:%02d</string>
        <string name="time_minutes_seconds_formatter" translatable="false">%02d:%02d</string>
        <string name="time_seconds_formatter" translatable="false">%02d</string>


        Then, manually I format it using function (in Kotlin):



         private fun formatTime(millis: Long): String 
        val hours = TimeUnit.MILLISECONDS.toHours(millis) % 24
        val minutes = TimeUnit.MILLISECONDS.toMinutes(millis) % 60
        val seconds = TimeUnit.MILLISECONDS.toSeconds(millis) % 60

        return when
        hours == 0L && minutes == 0L -> String.format(
        resources.getString(R.string.time_seconds_formatter), seconds
        )

        hours == 0L && minutes > 0L -> String.format(
        resources.getString(R.string.time_minutes_seconds_formatter), minutes, seconds
        )

        else -> resources.getString(R.string.time_hours_minutes_seconds_formatter, hours, minutes, seconds)








        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 7 at 17:07









        Michał PowłokaMichał Powłoka

        326214




        326214



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55048137%2fjava-kotlin-android-format-time-hhmmss-and-remove-unnecessary-zeros-from-t%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Obelisk of Theodosius Contents History Description Notes Bibliography Further reading External links Navigation menuAge of spirituality : late antique and early Christian art, third to seventh centuryOver 60 picturesObelisks of the World41°00′21.24″N 28°58′31.43″E / 41.0059000°N 28.9753972°E / 41.0059000; 28.97539727724550-7235741376235741376

            밀양 대씨 역사 각주 함께 보기 둘러보기 메뉴밀양 대씨

            1973년 목차 사건 문화 탄생 사망 노벨상 달력 둘러보기 메뉴