gpt4 book ai didi

java.text.ParseException 无法解析日期 : "0"

转载 作者:行者123 更新时间:2023-11-30 08:12:46 26 4
gpt4 key购买 nike

我正在尝试转换字符串

2010-03-09

输入日期,还可以获取一年中的第几天。

String dt = "2010-03-09";
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = new GregorianCalendar();
Date d = date.parse(dt);
cal.setTime(d);
int doy = cal.get(Calendar.DAY_OF_YEAR);

我不确定为什么会出现此错误

Exception in thread "main" java.text.ParseException: Unparseable date: "0"

作为我的参数的 SimpleDateFormat 字符串模式有问题吗?

我的条件严格要求字符串的格式为

2010-03-09

Bc 我有一个包含 4000 个这种格式的日期的数组

任何帮助将不胜感激,我是日历、日期和 SimpleDateFormat 类的新手

我正在处理数组,上面的例子是一般情况。这是我正在处理的实际案例

public static int[] todoy(String[] dt) {        // input array of String (dates) and will return array of DOY's
int[] re = new int[size];
Date d = null;
for (int i=0;i<size;i++){
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = new GregorianCalendar();
try {
d = date.parse(dt[i]);
} catch (ParseException e) {
e.printStackTrace();
}
cal.setTime(d);
re[i] = cal.get(Calendar.DAY_OF_YEAR);

}//fill in array of DOY's
return re;
}//inputs date such as 5/2 and returns integer for which day of the year it is

最佳答案

你能试试这个代码吗?

  public static int[] todoy(String[] dt) {        // input array of String (dates) and will return array of DOY's
int[] re = new int[size];
Date d = null;
if(dt == null) return null;

for (int i=0;i<size;i++){
if(dt[i] != null && dt[i] != "0") {
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = new GregorianCalendar();
try {
d = date.parse(dt[i]);
} catch (ParseException e) {
e.printStackTrace();
}
if(d != null ) {
cal.setTime(d);
re[i] = cal.get(Calendar.DAY_OF_YEAR);
}
}
}//fill in array of DOY's
return re;
}

您需要用 try-catch 子句包围您的 parse 方法。其中一项条目的格式似乎不正确。当您捕获该异常时,您可以检查到底是什么原因。

关于java.text.ParseException 无法解析日期 : "0",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30134630/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com