使用今天,昨天,明天等字符串格式化日期的正确方法

时间:2011-09-18 14:21:49

标签: android algorithm design-patterns datetime

我有一个日期textview。我的textview包含一个类似2011.09.17的日期字符串。好吧,我仍然希望有这个,但我也想为今天或昨天的某些特定日期添加更多用户友好的信息。例如,如果今天是2011.09.17,我希望我的textview具有昨天的价值,而不是2011.09.16,而今天则是2011.09.17。

好吧,我已经设法做到这一点:),但是以丑陋的方式:(。我用很多'if->而不是'真的很丑陋,我想要添加一些新规则如果日期超过一年我想把字符串放在去年左右......我真的需要添加丑陋的逻辑。

我的问题是有更好的方法吗?这有什么类似于设计模式的东西吗?建议的方法是什么?我相信很多人都遇到过这种问题

如果有一些沐浴方法而不是数千个ifs?如果不是谢谢,至少我会停止寻找沐浴者解决方案

任何建议,摘录等都将受到赞赏

谢谢

6 个答案:

答案 0 :(得分:43)

您可以在DateUtils中尝试getRelativeDateTimeString http://developer.android.com/reference/android/text/format/DateUtils.html

答案 1 :(得分:10)

我通常使用这个方便的java库进行相对时间格式化。 Prety Time Library

答案 2 :(得分:4)

public class RelativeWeekday {                
    private final Calendar mCalendar;                

    public RelativeWeekday(Calendar calendar) {                
        mCalendar = calendar;                
    }                

    @Override                
    public String toString() {                
        Calendar today = Calendar.getInstance(Locale.getDefault());
        int dayOfYear = mCalendar.get(Calendar.DAY_OF_YEAR);
        if (Math.abs(dayOfYear - today.get(Calendar.DAY_OF_YEAR)) < 2) {
            return getRelativeDay(today);
        }              

        return getWeekDay();                
    }                

    private String getRelativeDay(Calendar today) {                
        return DateUtils.getRelativeTimeSpanString(                
                mCalendar.getTimeInMillis(),                
                today.getTimeInMillis(),                
                DateUtils.DAY_IN_MILLIS,                
                DateUtils.FORMAT_SHOW_WEEKDAY).toString();                
    }                

    private String getWeekDay() {                
        SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE");                
        return dayFormat.format(mCalendar.getTimeInMillis());                
    }                
}

答案 3 :(得分:0)

试试这个,我使用joda-datatime2.2.jar和java SimpleDateFormat实现它

import java.text.SimpleDateFormat;
import java.util.Date;
import org.joda.time.DateMidnight;
import org.joda.time.DateTime;
import org.joda.time.Days;
public class SmartDateTimeUtil {
private static String getHourMinuteString(Date date){
    SimpleDateFormat hourMinuteFormat = new SimpleDateFormat(" h:m a");
    return hourMinuteFormat.format(date);
}

private static String getDateString(Date date){
    SimpleDateFormat dateStringFormat = new SimpleDateFormat("EEE',' MMM d y',' h:m a");
    return dateStringFormat.format(date);
}

private static boolean isToday (DateTime dateTime) {
       DateMidnight today = new DateMidnight();
       return today.equals(dateTime.toDateMidnight());
}

private static boolean isYesterday (DateTime dateTime) {
       DateMidnight yesterday = (new DateMidnight()).minusDays(1);
       return yesterday.equals(dateTime.toDateMidnight());
}

private static boolean isTomorrow(DateTime dateTime){
    DateMidnight tomorrow = (new DateMidnight()).plusDays(1);
       return tomorrow.equals(dateTime.toDateMidnight());
}
private static String getDayString(Date date) {
        SimpleDateFormat weekdayFormat = new SimpleDateFormat("EEE',' h:m a");
        String s;
        if (isToday(new DateTime(date)))
            s = "Today";
        else if (isYesterday(new DateTime(date)))
            s = "Yesterday," + getHourMinuteString(date);
        else if(isTomorrow(new DateTime(date)))
            s = "Tomorrow," +getHourMinuteString(date);
        else
            s = weekdayFormat.format(date);
        return s;
}

public static String getDateString_shortAndSmart(Date date) {
        String s;
        DateTime nowDT = new DateTime();
        DateTime dateDT = new DateTime(date);
        int days = Days.daysBetween(dateDT, nowDT).getDays();   
        if (isToday(new DateTime(date)))
            s = "Today,"+getHourMinuteString(date);
        else if (days < 7)
            s = getDayString(date);
        else
            s = getDateString(date);
        return s;
}

}

使用和测试Util类的简单案例:

import java.util.Calendar;
import java.util.Date;

public class SmartDateTimeUtilTest {
    public static void main(String[] args) {
        System.out.println("Date now:"+SmartDateTimeUtil.getDateString_shortAndSmart(new Date()));
        System.out.println("Date 5 days before :"+SmartDateTimeUtil.getDateString_shortAndSmart(getFutureDay(-5)));
        System.out.println("Date 1 day before :"+SmartDateTimeUtil.getDateString_shortAndSmart(getFutureDay(-1)));
        System.out.println("Date last month:"+SmartDateTimeUtil.getDateString_shortAndSmart(getFutureMonth(-1)));
        System.out.println("Date last year:"+SmartDateTimeUtil.getDateString_shortAndSmart(getFutureDate(-1)));
        System.out.println("Date 1 day after :"+SmartDateTimeUtil.getDateString_shortAndSmart(getFutureDay(1)));
    }
    public static Date getFutureDate(int numberOfYears){
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.YEAR, numberOfYears); 
        return c.getTime();
    }
    public static Date getFutureMonth(int numberOfYears){
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.MONTH, numberOfYears); 
        return c.getTime();
    }

    public static Date getFutureDay(int numberOfYears){
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DATE, numberOfYears); 
        return c.getTime();
    }
}

答案 4 :(得分:0)

getRelativeTimeSpanString 已在API级别3中添加

getRelativeTimeSpanString(长时间,                 很久以前                 minResolution长)

返回一个字符串,该字符串将“时间”描述为相对于“现在”的时间。

过去的时间跨度格式设置为“ 42分钟前”。未来的时间跨度格式为“在42分钟内”。 您可以在此处找到更多信息:

https://developer.android.com/reference/android/text/format/DateUtils

    Calendar now = Calendar.getInstance();
    return DateUtils.getRelativeTimeSpanString(time, now.getTimeInMillis(), DateUtils.DAY_IN_MILLIS);

答案 5 :(得分:-1)

对于android在build.gradle文件中使用JodaTime库:

  

编译'net.danlew:android.joda:2.9.9'

public static String formateddate(String date) {
    DateTime dateTime = DateTimeFormat.forPattern("dd-MMM-yyyy").parseDateTime(date);
    DateTime today = new DateTime();
    DateTime yesterday = today.minusDays(1);
    DateTime twodaysago = today.minusDays(2);
    DateTime tomorrow= today.minusDays(-1);

    if (dateTime.toLocalDate().equals(today.toLocalDate())) {
        return "Today ";
    } else if (dateTime.toLocalDate().equals(yesterday.toLocalDate())) {
        return "Yesterday ";
    } else if (dateTime.toLocalDate().equals(twodaysago.toLocalDate())) {
        return "2 days ago ";
    } else if (dateTime.toLocalDate().equals(tomorrow.toLocalDate())) {
        return "Tomorrow ";
    } else {
        return date;
    }
}