【问题标题】:Getting Blank Date as string from a custom date method从自定义日期方法获取空白日期作为字符串
【发布时间】:2018-02-12 19:23:08
【问题描述】:

我正在制作一个日期过滤器,为此我创建了一个自定义方法,以便以特定日期格式解析日期。 我有两种格式 dd MMM yyyy 和 yyyy-mm-dd 的日期,它在一个方法中传递,以 yyyy-mm-dd 格式进行解析和返回。 由于我在末尾有一个复杂的结构,两种类型的格式化字符串都将采用日期解析方法。

ISSUE:: 当格式为 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

【问题讨论】:

  • 方法 retun current_date null 并且您需要它返回像这样的格式化日期 yyyy-mm-dd???
  • 当我运行你的代码时,我从java.text.ParseException: Unparseable date: "2017-04-02" 得到一个堆栈跟踪。如果您没有在计算机上看到此堆栈跟踪或此异常,则您的项目设置中存在严重缺陷,该缺陷隐藏了有关错误的重要信息。如果是这样,我建议您首先修复您的设置,然后再寻找如何从程序中获得所需输出的解决方案。 :-) 同样在我的计算机上,您的日志语句正在打印一些东西。

标签: java android date datetime pattern-matching


【解决方案1】:

如您所愿,结果格式如: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;
}

【讨论】:

    猜你喜欢
    • 2023-02-16
    • 2015-11-26
    • 2013-03-07
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    相关资源
    最近更新 更多