我喜欢在我的PHP项目中使用SupportDate
类,以便像使用工具箱一样使用它,所以我也会在我的Android项目中使用它。Java/Android:如何格式化日期?
长的故事作了简短:
这是SupportDate
类:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/**
* Created by Alessandro on 28/06/2015.
*/
public class SupportDate {
// Suppress default constructor for noninstantiability
private SupportDate() {
throw new AssertionError();
}
public static String getCurrentDate(String format) {
if (format==null){
format = "yyyy-MM-dd HH:mm:ss";
}
final SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
final String utcTime = sdf.format(new Date());
return utcTime;
}
public static String formatDate(String date, String format){
if (date==null){
date = getCurrentDate(null);
}
if (format==null){
format = "dd-MM-yyyy";
}
final SimpleDateFormat sdf = new SimpleDateFormat(format);
final String formattedDate = sdf.format(date);
return formattedDate;
}
}
这是我的使用,从数据库中检索到的值:
last_event_placeholder.append(SupportDate.formatDate(last_event,null));
的last_event
值是从SQLlite检索到的字符串:2015-06-29 10:41:12
并在日志中的错误是
java.lang.IllegalArgumentException: Bad class: class java.lang.String
的方法formatDate
的final String formattedDate = sdf.format(date);
排谢谢你的帮助
你最关心的是什么?你想格式化日期? –
是的,我想格式化日期dinamyc,在方法中传递格式作为参数。谢谢 – sineverba
我不明白你想要什么。我给'20150303'和'yyyyMMdd'格式,是否返回字符串'2015-03-03 00:00:00'?而你使用SimpleDateFormat.format错误。它应该把Date对象作为参数,而不是String。 http://developer.android.com/reference/java/text/DateFormat.html#format(java.util.Date) – calvinfly