我的服务器返回一段时间前的字符串格式,例如2分钟前
,这很好,但我现在需要将其转换为秒。我想只使用空格分隔符分割字符串并获取第一个文本,但是,在某些情况下,我的服务器返回 5 小时 43 分钟前
等的实例。我的问题是,是否有考虑到这些情况,从现在的格式转换为仅几秒的巧妙方法?
最佳答案
我认为没有特定的库或方法可以将“时间之前”转换为秒。对您来说最好的选择是解析服务器返回的“Time ago”字符串并自行进行转换。最简单的方法是在空间边界上分割字符串,然后获取小时和分钟的值。
public static int timeAgoToSeconds(String timeAgo) {
int timeInSec = 0;
String []myStringArray = timeAgo.trim().split(" ");
if(myStringArray.length==3){
timeInSec = Integer.valueOf(myStringArray[0]) *60;
}
if(myStringArray.length==5){
timeInSec = Integer.valueOf(myStringArray[0]) *3600 + Integer.valueOf(myStringArray[2]) * 60;
}
return timeInSec;
}
在main()方法中测试:
String timeAgoHHmm = "5 hour 43 minutes ago";
String timeAgoMM = "2 minutes ago";
System.out.println(timeAgoToSeconds(timeAgoHHmm));//20580
System.out.println(timeAgoToSeconds(timeAgoMM));//120
关于java - 在android中将 "time ago"转换为秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40700069/