Android:将字符串转换为时间



我试图将包含时间戳的字符串转换为与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天前"等。

编辑:对不起,我也写了一个toast函数。

public void toast(String text){
    Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}

使用SimpleDateFormat和它的parse()函数将时间戳从字符串转换为Date对象。之后,您可以使用Date.getTime()在ms中获得时间戳的长值

请检查下面的代码,我已经修改了它,这可能解决你的问题:

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

我认为你叫toast的方式是不对的。

试试这个链接,它会对你有更多的帮助。

烤面包。我给它取了个很疯狂的名字lol

你需要SimpleDateFormat
类似下面的代码可以帮助您
"format"是字符串日期的编码结构,如"dd MMM yyyy hh:mm:ss zzz"
"Value"是你的字符串日期。
有关SimpleDateFormat的格式和其他"方法"的详细信息,请参阅http://developer.android.com/reference/java/text/SimpleDateFormat.html

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 ();与"time"参数(长类型)兼容

最新更新