gpt4 book ai didi

java - 日期返回 null

转载 作者:行者123 更新时间:2023-12-01 22:21:09 25 4
gpt4 key购买 nike

我正在构建一个带有用户列表的 Android 应用程序,并且我正在尝试从用户那里获取年龄。

我从 json 文件获取所有数据,并且收到如下生日日期:

"birth_date":"1965-05-07"

现在,我正在尝试解析年、月和日期,并从用户那里获取年龄。

for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);

String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String user_id = c.getString(TAG_USERID);
String birth_date = c.getString(TAG_BIRTH_DATE);
String pic_url_get = c.getString(TAG_IMAGE);

int year = Integer.parseInt(birth_date.substring(0, 4));
int month = Integer.parseInt(birth_date.substring(4, 6));
int day = Integer.parseInt(birth_date.substring(birth_date.length() - 2));

Calendar dateOfYourBirth = new GregorianCalendar(year, month, day);
Calendar today = Calendar.getInstance();
int yourAge = today.get(Calendar.YEAR) - dateOfYourBirth.get(Calendar.YEAR);
dateOfYourBirth.add(Calendar.YEAR, yourAge);
if (today.before(dateOfYourBirth)) {
yourAge--;
}

// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();

// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_BIRTH_DATE, "Age" + yourAge);
contact.put(TAG_IMAGE, "*******/images/" + user_id + "/" + pic_url_get);


// adding contact to contact list
contactList.add(contact);
}

我收到的错误:

04-19 16:32:20.091: E/AndroidRuntime(19736): Caused by: java.lang.NumberFormatException: Invalid int: "null"
04-19 16:32:20.091: E/AndroidRuntime(19736): at java.lang.Integer.invalidInt(Integer.java:138)
04-19 16:32:20.091: E/AndroidRuntime(19736): at java.lang.Integer.parse(Integer.java:375)
04-19 16:32:20.091: E/AndroidRuntime(19736): at java.lang.Integer.parseInt(Integer.java:366)
04-19 16:32:20.091: E/AndroidRuntime(19736): at java.lang.Integer.parseInt(Integer.java:332)

我该如何解决这个问题?

最佳答案

不要重新发明the wheel :

// replace your birth_date substring calls with this
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");
DateTime birthDate = fmt.parse(birth_date);

关于java - 日期返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29731951/

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