2015-06-29 64 views
-1

我喜欢在我的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);排谢谢你的帮助

+0

你最关心的是什么?你想格式化日期? –

+0

是的,我想格式化日期dinamyc,在方法中传递格式作为参数。谢谢 – sineverba

+0

我不明白你想要什么。我给'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

回答

7

DateFormat.format预计数字或日期,但你正在传递一个字符串。通过你的日期字符串之前,你应该把它解析为一个日期,例如像这样:

DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS"); 
Date inputDate = inputFormat.parse(date); 

,然后通过这个inputDate您的SimpleDateFormatlikе这样的:

final String formattedDate = sdf.format(inputDate); 

希望这有助于你:)

PS在这里你可以找到更多的答案Caused by: java.lang.IllegalArgumentException: Bad class: class java.lang.String

0

我使用我自己的方法,你必须通过输入格式,输入日期时间戳字符串和预期的日期格式来获取日期值在字符串中。 试试这个:

public static String getDesired(String desiredDateFormat, String inputFormat,String inputStringDate) { 

     try { 
      Date date = (new SimpleDateFormat(inputFormat)).parse(inputStringDate); 
      return (new SimpleDateFormat(desiredDateFormat)).format(date); 

     } catch (ParseException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    }