Android: getRelativeTime example

后端 未结 2 1438
青春惊慌失措
青春惊慌失措 2020-12-29 07:33

Can someone show me an example how to properly use the getRelativeDateTimeString() that is detailed here.

相关标签:
2条回答
  • 2020-12-29 07:53

    I think a better question would specify what you want as an output. However, here's an example:

     DateUtils.getRelativeTimeSpanString(yourContext, theEventInMillis, 
                                         DateUtils.MINUTE_IN_MILLIS, 
                                         DateUtils.FORMAT_NO_NOON);
    

    This will format theEventInMillis relative to whatever the system's current time is. It will show changes in minutes (0 minutes ago, 2 minutes ago, 3 hours ago, 1 day ago, etc) until the difference reaches a week, then it will just post the full date. The flags field (0 in this case, last argument) you can use to control how the resulting string is rendered, but you should check the docs to see what fits your needs.

    0 讨论(0)
  • 2020-12-29 08:03

    I guess you are talking about getRelativeDateTimeString, which is pointed to by your link.

    Example for now, with comments detailing all params:

    Date now = new Date();
    String str = DateUtils.getRelativeDateTimeString(
    
            this, // Suppose you are in an activity or other Context subclass
    
            now.getTime(), // The time to display
    
            DateUtils.MINUTE_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
    

    Other values for MINUTE_IN_MILLIS and YEAR_IN_MILLIS include:

    • SECOND_IN_MILLIS
    • MINUTE_IN_MILLIS
    • HOUR_IN_MILLIS
    • DAY_IN_MILLIS
    • WEEK_IN_MILLIS
    • YEAR_IN_MILLIS
    • Any custom value in milliseconds
    0 讨论(0)
提交回复
热议问题