我需要知道在android开发中是否有类似时间的东西?在android开发中有没有像TimeSpan的东西?
在C#有类似的东西,我喜欢以两种方式使用它:
- 生成一个时间跨度,然后添加例如分钟,然后显示整个跨度
- 产生两个日期时间之间的时间跨度(什么是Android的等效的DateTime?)
我需要知道在android开发中是否有类似时间的东西?在android开发中有没有像TimeSpan的东西?
在C#有类似的东西,我喜欢以两种方式使用它:
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();
}
通的日期和时间,它会返回修改的时间......
不幸的是,没有像TimeSpan
类在Java中还提供原生的,但你可以用几行代码实现这一目标。在秒
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;
Android有DateUtils,方法“formatElapsedTime”做你所需要的,如果你给它正确的输入。
Java中的日期很尴尬。看看https://github.com/dlew/joda-time-android
你可以很容易地得到“TimeSpan”以毫秒为单位。要将毫秒转换为格式化的数字,您可以在您的功能中做一些快速而优雅的计算,例如
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);
}