Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/217.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java(Android)将SQLite日期转换为;“x天前”;_Java_Android_Date_Format - Fatal编程技术网

Java(Android)将SQLite日期转换为;“x天前”;

Java(Android)将SQLite日期转换为;“x天前”;,java,android,date,format,Java,Android,Date,Format,我有: 我想解析该字符串,然后从当前日期/时间中减去该日期/时间,这样我就可以输出类似于“2天前”的字符串。将其转换为日期。获取当前日期时间。计算差异 也许有更好的方法,但这是可行的 String date = "2010-10-9 12:00:00"; 这是我正在使用的一个助手类,它扩展了Android的标准DateUtils。它有一个高级逻辑,对于今天的时间戳,它将显示秒、分钟或小时,而对于其他时间戳,它将显示日期 您可以在getTimeDiffString方法中根据需要调整逻辑。作为参数

我有:


我想解析该字符串,然后从当前日期/时间中减去该日期/时间,这样我就可以输出类似于“2天前”的字符串。

将其转换为日期。获取当前日期时间。计算差异

也许有更好的方法,但这是可行的

String date = "2010-10-9 12:00:00";

这是我正在使用的一个助手类,它扩展了Android的标准DateUtils。它有一个高级逻辑,对于今天的时间戳,它将显示秒、分钟或小时,而对于其他时间戳,它将显示日期

您可以在
getTimeDiffString
方法中根据需要调整逻辑。作为参数,您将解析
Date-Date=formatter.parse(dateString)的时间戳您正在获取上面的代码

代码逻辑符合“时间戳显示”,正如您从Facebook或Twitter所知道的那样

String dateString = "2010-10-9 12:00:00";
String daysAgo = null;
// How many milliseconds in 1 day
final long DAY_IN_MILLIS = 86400000;
// The current timestamp in milliseconds
long now = System.currentTimeMillis();
// The format of your date string assuming the 1 am would read 01:00, not 1:00
// and Jan 1, 2010 would read 2010-1-1, not 2010-01-01
final DateFormat formatter = new SimpleDateFormat("yyyy-M-d hh:mm:ss");
// The calendar instance which adds a locale to the date
final Calendar cal = Calendar.getInstance();
try {
    // Parse the date string to return a Date object
    Date date = formatter.parse(dateString);
    // Set the calendar with our date object
    cal.setTime(date);
    // Get the millis timestamp of your date string
    long then = cal.getTimeInMillis();
    // Calculate the difference
    long difference = now - then;
    int ago = 0;
    // If the difference is greater than one day
    if (difference >= DAY_IN_MILLIS) {
        // Find the product
        ago = (int) (difference / DAY_IN_MILLIS);
        // Format your new string
            // You may want to check if(ago>1) here
        daysAgo = String.format("%d day(s) ago", ago);
    }
    // Write the result to Logcat
    Log.d(TAG, daysAgo);

} catch (ParseException e) {
    Log.e(TAG, e.getLocalizedMessage());
}   
公共类DateTimeUtils扩展了DateUtils{
私有静态字符串MTIMESTAMPLABELLOY;
私有静态字符串mTimestampLabelToday;
私有静态字符串mTimestampLabelJustNow;
私有静态字符串mTimestampLabelMinutesAgo;
私有静态字符串mTimestampLabelHoursAgo;
私有静态字符串mTimestampLabelHourAgo;
/**
*Singleton构造函数,需要访问i18n的应用程序上下文和字符串
*@param上下文
*@return DateTimeUtils singleton instancec
*@抛出异常
*/
公共静态DateTimeUtils getInstance(上下文){
mCtx=上下文;
if(实例==null){
实例=新的DateTimeUtils();
MTIMestamplabelDayed=context.getResources().getString(R.string.WidgetProvider\u timestamp\u Dayed);
mTimestampLabelToday=context.getResources().getString(R.string.WidgetProvider\u timestamp\u today);
mTimestampLabelJustNow=context.getResources().getString(R.string.WidgetProvider\u timestamp\u justnow);
mTimestampLabelMinutesAgo=context.getResources().getString(R.string.WidgetProvider\u timestamp\u minutes\u ago);
mTimestampLabelHoursAgo=context.getResources().getString(R.string.WidgetProvider\u timestamp\u hours\u ago);
mTimestampLabelHourAgo=context.getResources().getString(R.string.WidgetProvider\u时间戳\u小时前);
}
返回实例;
}
/**
*检查给定日期是否为昨天。
*
*@param date-要检查的日期。
*@如果日期是昨天,则返回TRUE,否则返回FALSE。
*/
昨天(长日期)的公共静态数据{
最终日历currentDate=Calendar.getInstance();
currentDate.setTimeInMillis(日期);
final Calendar yesterdayDate=Calendar.getInstance();
添加(Calendar.DATE,-1);
返回yesterdayDate.get(Calendar.YEAR)=currentDate.get(Calendar.YEAR)和&yesterdayDate.get(Calendar.DAY\u OF年)==currentDate.get(Calendar.DAY\u OF年);
}
公共静态字符串[]weekdays=new DateFormatSymbols().getWeekdays();//获取日期名称
公共静态最终长毫秒每天=1000*60*60*24;
...
/**
*显示用户友好的日期差异字符串
*@param timedate Timestamp格式为从现在开始的日期差异
*@返回友好格式的日期差异字符串
*/
公共字符串getTimeDiffString(长时间日期){
Calendar startDateTime=Calendar.getInstance();
Calendar endDateTime=Calendar.getInstance();
endDateTime.setTimeInMillis(timedate);
长毫秒1=startDateTime.getTimeInMillis();
长毫秒2=endDateTime.getTimeInMillis();
长差=毫秒1-毫秒2;
长时间=差异/(60*60*1000);
长分钟=diff/(60*1000);
分钟=分钟-60*小时;
长秒=diff/(1000);
布尔值isToday=DateTimeUtils.isToday(timedate);
布尔值IsDayed=DateTimeUtils.IsDayed(timedate);
如果(小时数>0和小时数<12){
return hours==1?String.format(mTimestampLabelHourAgo,hours):String.format(mTimestampLabelHoursAgo,hours);
}否则,如果(小时0)
返回String.format(MTIMESTAMPLABELLMINUTESAGO,分钟);
否则{
立即返回mTimestampLabelJustNow;
}
}否则,如果(每天){
今天返回MTIMESTAMPLABELL;
}否则如果(昨天){
昨天返回MTIMESTAMPLABELL;
}else if(startDateTime.getTimeInMillis()-timedate
虽然strings.xml适用于:

public class DateTimeUtils extends DateUtils {

     private static String mTimestampLabelYesterday;
     private static String mTimestampLabelToday;
     private static String mTimestampLabelJustNow;
     private static String mTimestampLabelMinutesAgo;
     private static String mTimestampLabelHoursAgo;
     private static String mTimestampLabelHourAgo;

    /**
     * Singleton contructor, needed to get access to the application context & strings for i18n
     * @param context Context
     * @return DateTimeUtils singleton instanec
     * @throws Exception
     */
     public static DateTimeUtils getInstance(Context context) {
         mCtx = context;
         if (instance == null) {
             instance = new DateTimeUtils();
             mTimestampLabelYesterday = context.getResources().getString(R.string.WidgetProvider_timestamp_yesterday);
             mTimestampLabelToday = context.getResources().getString(R.string.WidgetProvider_timestamp_today);
             mTimestampLabelJustNow = context.getResources().getString(R.string.WidgetProvider_timestamp_just_now);
             mTimestampLabelMinutesAgo = context.getResources().getString(R.string.WidgetProvider_timestamp_minutes_ago);
             mTimestampLabelHoursAgo = context.getResources().getString(R.string.WidgetProvider_timestamp_hours_ago);
             mTimestampLabelHourAgo = context.getResources().getString(R.string.WidgetProvider_timestamp_hour_ago);
         }
         return instance;
     }

    /**
     * Checks if the given date is yesterday.
     *
     * @param date - Date to check.
     * @return TRUE if the date is yesterday, FALSE otherwise.
     */
    public static boolean isYesterday(long date) {

        final Calendar currentDate = Calendar.getInstance();
        currentDate.setTimeInMillis(date);

        final Calendar yesterdayDate = Calendar.getInstance();
        yesterdayDate.add(Calendar.DATE, -1);

        return yesterdayDate.get(Calendar.YEAR) == currentDate.get(Calendar.YEAR) && yesterdayDate.get(Calendar.DAY_OF_YEAR) == currentDate.get(Calendar.DAY_OF_YEAR);
    }

    public static String[] weekdays = new DateFormatSymbols().getWeekdays(); // get day names
    public static final long millisInADay = 1000 * 60 * 60 * 24;


    ...

    /**
     * Displays a user-friendly date difference string
     * @param timedate Timestamp to format as date difference from now
     * @return Friendly-formatted date diff string
     */
    public String getTimeDiffString(long timedate) {
        Calendar startDateTime = Calendar.getInstance();
        Calendar endDateTime = Calendar.getInstance();
        endDateTime.setTimeInMillis(timedate);
        long milliseconds1 = startDateTime.getTimeInMillis();
        long milliseconds2 = endDateTime.getTimeInMillis();
        long diff = milliseconds1 - milliseconds2;

        long hours = diff / (60 * 60 * 1000);
        long minutes = diff / (60 * 1000);
        minutes = minutes - 60 * hours;
        long seconds = diff / (1000);

        boolean isToday = DateTimeUtils.isToday(timedate);
        boolean isYesterday = DateTimeUtils.isYesterday(timedate);

        if (hours > 0 && hours < 12) {
            return hours==1? String.format(mTimestampLabelHourAgo,hours) : String.format(mTimestampLabelHoursAgo,hours);
        } else if (hours <= 0) {
            if (minutes > 0)
                return String.format(mTimestampLabelMinutesAgo,minutes);
            else {
                return mTimestampLabelJustNow;
            }
        } else if (isToday) {
            return mTimestampLabelToday;
        } else if (isYesterday) {
            return mTimestampLabelYesterday;
        } else if (startDateTime.getTimeInMillis() - timedate < millisInADay * 6) {
            return weekdays[endDateTime.get(Calendar.DAY_OF_WEEK)];
        } else {
            return formatDateTime(mCtx, timedate, DateUtils.FORMAT_NUMERIC_DATE);
        }
    }

} 
今天
昨天
%一小时前
%几小时前
%几分钟前
刚才
试试这个:

<string name="WidgetProvider_timestamp_today">Today</string>
<string name="WidgetProvider_timestamp_yesterday">Yesterday</string>
<string name="WidgetProvider_timestamp_hour_ago">%s hour ago</string>
<string name="WidgetProvider_timestamp_hours_ago">%s hours ago</string>
<string name="WidgetProvider_timestamp_minutes_ago">%s minutes ago</string>
<string name="WidgetProvider_timestamp_just_now">Just now</string>

是的,这正是我想做的。现在,如果有人能告诉我怎么做,你必须导入java.text.DateFormatSymbols;导入java.util.Calendar;导入android.content.Context;导入android.text.format.DateUtils;并在类中声明两个变量:private static Context mCtx;私有静态DateTimeUtils实例;
    long currentTimeMillis = System.currentTimeMillis();
    CharSequence string = DateUtils.getRelativeTimeSpanString(currentTimeMillis, currentTimeMillis + DateUtils.MINUTE_IN_MILLIS * 5, 0, DateUtils.FORMAT_ABBREV_ALL);