Android开发中有类似TimeSpan的东西吗?

时间:2012-04-13 06:57:55

标签: android

我需要知道android开发中是否存在类似时间的东西?

在C#中有类似的东西,我喜欢以两种方式使用它:

  1. 生成一个时间跨度,然后添加例如分钟,然后显示整个范围
  2. 生成两个DateTime之间的时间跨度(android中DateTime的等价物是什么?)

5 个答案:

答案 0 :(得分:5)

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

} 

以秒为单位传递日期和时间,它将返回修改时间......

答案 1 :(得分:4)

不幸的是,Java中没有TimeSpan类似的类本身可用,但是你可以通过几行代码来实现这一点。

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;

答案 2 :(得分:2)

Android有DateUtils,如果你给它正确的输入,方法“formatElapsedTime”可以做你需要的。

答案 3 :(得分:0)

答案 4 :(得分:0)

Java中的日期很尴尬。看看https://github.com/dlew/joda-time-android