安卓:将字符串转换为一个时间 [英] Android: Convert string to a time

查看:219
本文介绍了安卓:将字符串转换为一个时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转换包含时间戳到时间与机器人RelativeDateTimeString一致的字符串,这样我就可以格式化它作为一个相对时间。我得到的时间戳格式为:

  2011-08-17 4点57分38秒
 

我想借这个字符串,并通过我的相对时间的功能在这里传递:

 公共无效RelativeTime(长时间){
    字符串str =(字符串)DateUtils.getRelativeDateTimeString(

            对此,//假设你是在一个活动或其他语境下的子类

            时间,//显示时间

            DateUtils.SECOND_IN_MILLIS,//决议。这将显示只有几分钟的路程
                              //(无三分钟前

            DateUtils.WEEK_IN_MILLIS,//最高分辨率时的时间将切换
                             //为默认跨度之日起代替。这会不会
                             //显示3个星期前,而是一个完整的日期,而不是

            0); //  - 最终标志

    吐司(STR);

}
 

因此​​函数应显示2天前的敬酒等。

谢谢!

编辑:对不起,我有一个敬酒的功能我写以及

 公共无效吐司(字符串文本){
    Toast.makeText(getApplicationContext(),文本,Toast.LENGTH_SHORT).show();
}
 

解决方案

使用的SimpleDateFormat 和它的解析()函数的时间戳转换一个字符串日期对象。之后,你可以使用 Date.getTime()来得到毫秒的时间戳的长期价值。

I am trying to convert a string that contains a time stamp to a time that is consistent with androids RelativeDateTimeString, so I can format it as a relative time. The time stamps that I get are in this format:

2011-08-17 04:57:38

I would like to take that string and pass it through my relative time function here:

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

}

So the function should show a toast of "2 days ago" etc.

Thanks!

EDIT: Sorry I have a toast function I've written as well.

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

解决方案

Use SimpleDateFormat and it's parse() function to convert your timestamp from a string to a Date object. After that you can use Date.getTime() to get the long value of your timestamp in ms.

这篇关于安卓:将字符串转换为一个时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆