我正在尝试将包含时间戳的字符串转换为与androids RelativeDateTimeString一致的时间,因此我可以将其格式化为相对时间。我得到的时间戳采用以下格式:
2011-08-17 04:57:38
我想把这个字符串传递给我的相对时间函数:
public void RelativeTime(Long time){
String str = (String) DateUtils.getRelativeDateTimeString(
this, // Suppose you are in an activity or other Context subclass
time, // The time to display
DateUtils.SECOND_IN_MILLIS, // The resolution. This will display only minutes
// (no "3 seconds ago"
DateUtils.WEEK_IN_MILLIS, // The maximum resolution at which the time will switch
// to default date instead of spans. This will not
// display "3 weeks ago" but a full date instead
0); // Eventual flags
toast(str);
}
因此该功能应该显示“2天前”的祝酒词等。
谢谢!
编辑:对不起,我也有写过的吐司功能。public void toast(String text){
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
答案 0 :(得分:4)
使用SimpleDateFormat及其parse()
函数将时间戳从字符串转换为Date
对象。之后,您可以使用Date.getTime()
以ms为单位获取时间戳的长值。
答案 1 :(得分:1)
请检查我修改过的以下代码,这可以解决您的问题:
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a", Locale.US);
Date now = formatter.parse("2014-01-26 05:36:38 PM");
Calendar calendar=Calendar.getInstance(Locale.US);
calendar.setTime(now);
RelativeTime(now.getTime());
} catch (Exception e) {
e.printStackTrace();
}
public void RelativeTime(Long time){
String str = (String) DateUtils.getRelativeDateTimeString(
this, // Suppose you are in an activity or other Context subclass
time, // The time to display
DateUtils.SECOND_IN_MILLIS, // The resolution. This will display only minutes
// (no "3 seconds ago"
DateUtils.WEEK_IN_MILLIS, // The maximum resolution at which the time will switch
// to default date instead of spans. This will not
// display "3 weeks ago" but a full date instead
0); // Eventual flags
toast(str);
}
public void toast(String text){
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
答案 2 :(得分:0)
答案 3 :(得分:0)
你需要SimpleDateFormat
类似下面的代码可能会帮助你
“格式”是您的字符串日期的编码结构,例如“dd MMM yyyy hh:mm:ss zzz”
代码中的“Value”是您的字符串日期
请参阅http://developer.android.com/reference/java/text/SimpleDateFormat.html以获取有关SimpleDateFormat
SimpleDateFormat sf = new SimpleDateFormat(format);
sf.setTimeZone(TimeZone.getTimeZone("UTC"));
//sf.setCalendar(Calendar.getInstance());
ParsePosition pp = new ParsePosition(0);
Date date = sf.parse(Value,pp);
if (pp.getIndex() == 0) {
Log.e(TAG,"Can't getDate with format:\""+format+"\" and value:\""+Value + "\" at char index:"+pp.getErrorIndex());
return Calendar.getInstance();
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.getTimeInMillis();与您的“时间”参数(长型)兼容