Is there something like TimeSpan in android development?

后端 未结 6 500
盖世英雄少女心
盖世英雄少女心 2021-01-12 05:29

I need to know if there is something like a timespan in android development?

in C# there is something like and I like to use it in two ways:

  1. generate a
相关标签:
6条回答
  • 2021-01-12 06:01

    Dates in Java are awkward. Have a look at https://github.com/dlew/joda-time-android

    0 讨论(0)
  • 2021-01-12 06:03

    Unfortunately, there's no TimeSpan like class yet natively available in Java, but you can achieve this with few lines of code.

    Calendar startDate = getStartDate();
    Calendar endDate = getEndDate();
    
    long totalMillis = endDate.getTimeInMillis() - startDate.getTimeInMillis();
    int seconds = (int) (totalMillis / 1000) % 60;
    int minutes =  ((int)(totalMillis / 1000) / 60) % 60;
    int hours = (int)(totalMillis / 1000) / 3600;
    
    0 讨论(0)
  • 2021-01-12 06:06

    Android has DateUtils, the method "formatElapsedTime" does what you need if you give it the right input.

    0 讨论(0)
  • 2021-01-12 06:18

    You can easily get the "TimeSpan" in milliseconds. To convert milliseconds to a formatted one, you can do a little fast and elegant calculation in your function like this,

    public static String GetFormattedTimeSpan(final long ms) {
        long x = ms / 1000;
        long seconds = x % 60;
        x /= 60;
        long minutes = x % 60;
        x /= 60;
        long hours = x % 24;
        x /= 24;
        long days = x;
    
        return String.format("%d days %d hours %d minutes %d seconds", days, hours, minutes, seconds);
    }
    
    0 讨论(0)
  • 2021-01-12 06:24
    public long addSeconds(long dt,int sec) //method to add seconds in time  
    {
    
        Date Dt = new Date(dt);
        Calendar cal = new GregorianCalendar();
    
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
        sdf.setCalendar(cal);
        cal.setTimeInMillis(Dt.getTime());
        cal.add(Calendar.SECOND, sec);
        return cal.getTime().getTime();
    
    } 
    

    pass date and time in sec, it will return modified time...

    0 讨论(0)
  • 2021-01-12 06:25

    You can use the Calendar class.

    http://tutorials.jenkov.com/java-date-time/java-util-calendar.html

    0 讨论(0)
提交回复
热议问题