我有一个问题,我尝试从网络服务显示日期,并显示所有日期,
例如"23 mai 2013 11:05:01 GMT"
我希望像这样展示"today at 9h30"
,
这就是我所做的:
public Date getDate() {
return pubdate;
}
public void setDate(String date) {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
this.pubdate = fmt.parse(date);
} catch (Exception e) {
e.printStackTrace();
}
}
TextView textedate= (TextView) view.findViewById(R.id.textArticleDate);
txtArticleDate.setText(article.getDate().toGMTString());
我能做些什么才能像今天或昨天一样展示......?
答案 0 :(得分:1)
好的,这只是一个例子......试试吧
public class StackExampleDate {
Date pubdate;
public static void main(String[] args){
try {
setDate("23 mai 2013 11:05:01 GMT");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Date getDate() {
return pubdate;
}
public static void setDate(String date) throws ParseException {
//MMMM = Month as text , z = time zone, ' = character for text
SimpleDateFormat fmt_in = new SimpleDateFormat("dd MMMM yyyy HH:mm:ss z");
SimpleDateFormat fmt_out = new SimpleDateFormat("'at' H'h'mm");
Date date_in = fmt_in.parse(date);
String output_date_string = fmt_out.format(date_in);
if(isToday(date_in)){
System.out.println("today "+output_date_string);
}else{
System.out.println("Some day "+output_date_string);
}
}
public static boolean isToday(Date date) {
return isSameDay(date, Calendar.getInstance().getTime());
}
public static boolean isSameDay(Date date1, Date date2) {
if (date1 == null || date2 == null) {
throw new IllegalArgumentException("The dates must not be null");
}
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
return isSameDay(cal1, cal2);
}
public static boolean isSameDay(Calendar cal1, Calendar cal2) {
if (cal1 == null || cal2 == null) {
throw new IllegalArgumentException("The dates must not be null");
}
return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR));
}
}
//如果结果时间不是您给定的时间..请查看您的时区GMT + n
答案 1 :(得分:0)
使用SimpleDateFormat类,您无法在今天或昨天显示。您必须使用字符串操作并获取日期,年份并与系统日期,年份进行比较并创建自己的字符串。
获取系统日期 - Calendar.getInstance().get(Calendar.DATE);
答案 2 :(得分:0)
你需要第二个dateformater ..例如
String strDate = "12/12/07";
try
{
//create SimpleDateFormat object with source string date format
SimpleDateFormat sdfSource = new SimpleDateFormat("dd/MM/yy");
//parse the string into Date object
Date date = sdfSource.parse(strDate);
//create SimpleDateFormat object with desired date format
SimpleDateFormat sdfDestination = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss");
//parse the date into another format
strDate = sdfDestination.format(date);
System.out.println("Date is converted from dd/MM/yy format to MM-dd-yyyy hh:mm:ss");
System.out.println("Converted date is : " + strDate);
}
catch(ParseException pe)
{
System.out.println("Parse Exception : " + pe);
}
和“今天”之类的东西比如if(date == today)比显示字符串“today at”,而不是缩短完整日期..