从自定义日期方法获取空白日期为字符串



我正在制作一个日期过滤器,我为其创建了一个自定义方法,以以特定日期格式解析日期。我有两种格式DD MMM Yyyy&YYYY-MM-DD以单个方法为解析并以Yyyy-Mm-DD的格式返回。由于我在两种格式的字符串结构处都具有复杂的结构。

问题::当格式在yyyy-mm-dd中时,我从此方法中获得了一个空白字符串。请给我我错了的意见。以下是代码

 //fetching date from methods
String current_date=CurrentFilterPeriod.dateParsing("2017-04-02");
String prev_date=CurrentFilterPeriod.dateParsing("01 Apr 2017");


//singleton file for date filter method
public class CurrentFilterPeriod {
    private static Calendar cal = getInstance();
    private static Date current_date = cal.getTime();
    //defined formats for date
    private static SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy");
    private static SimpleDateFormat formatterString = new SimpleDateFormat("yyyy-MM-dd");

//method for parsing date
public static String dateParsing(String date){
    Date newDate;
    String returnDate = "";
    if (date.equals(formatter.toPattern())){
        returnDate=date;
    }
    Log.e("DB","date===>"+date);
    try {
        newDate = formatter.parse(date);
        Log.e("DB","New Date===>"+newDate);
        returnDate=formatterString.format(newDate);
        Log.e("DB","returnDate===>"+returnDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }
        return returnDate;
}
}

结果:: current_date =" prev_date =" 2017-04-01"

我被困在这里,请帮助我或告诉我其他通过所需输出获得的方法。

您想要结果格式,例如: yyyy-mm-dd。您需要使用formatterString格式化日期字符串。

使用:

更改您的代码
 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
boolean isValidDate(String input) {
     try {
          format.parse(input);
          return true;
     }
     catch(ParseException e){
          return false;
     }
}

现在使用:

调用该方法
//method for parsing date
public static String dateParsing(String date) {
 Date newDate;
 String returnDate = "";
 if (isValidDate(date)) {
  returnDate = date;
  return returnDate;
 } else {
  Log.e("DB", "date===>" + date);
  try {
   newDate = formatter.parse(date);
   Log.e("DB", "New Date===>" + newDate);
   returnDate = formatterString.format(newDate);
   Log.e("DB", "returnDate===>" + returnDate);
  } catch (ParseException e) {
   e.printStackTrace();
  }
 }
 return returnDate;
}

最新更新