[英]Java String, indexof and substring to get a date parsed
essentially, what I am doing is getting a date such as "4/18/1972" and regurgitating it properly formatted "April 18, 1972". 本质上,我正在做的是获取一个日期,例如“ 4/18/1972”,然后重新格式化为“ 1972年4月18日”。 I was able to get past the first hurdle, 我能够克服第一个障碍,
Here's the code I have initially to build it: 这是我最初要构建它的代码:
System.out.print("Date: ");
receivedDate = user.next();
String receivedDateMonth = receivedDate.substring(0, receivedDate.indexOf("/"));
int receivedMonth = Integer.parseInt(receivedDateMonth);
if(month >= 1 && month <= 9)
{
String receivedDateDay = receivedDate.substring(2, receivedDate.indexOf("/"));
int day = Integer.parseInt(receivedDateDay);
System.out.println(day);
}
As I wrote it, I was testing to make sure receivedDateMonth appears properly and it did, but as I move onto the day, it doesn't work. 在撰写本文时,我正在测试以确保ReceivedDateMonth正确显示并且确实显示,但是随着时间的推移,它不起作用。 I keep getting an error, "String index out of range: -1". 我不断收到错误消息,“字符串索引超出范围:-1”。 I figure it's centered on the "2" there, so I changed its value and the problem persists. 我认为它以“ 2”为中心,因此我更改了它的值,问题仍然存在。 I put the 2 in because I wanted it to count from the first digit, 0, then the "/", with the intention of starting the next parse after that(I would change the 10-12 to do similar, go to 3), however, for the life of me, I cannot figure this out. 我输入2是因为我希望它从第一个数字0开始,然后从“ /”开始计数,目的是在此之后开始下一个解析(我将10-12更改为类似的数字,转到3)但是,对于我的一生,我无法弄清楚。 Could someone please point me in the right direction? 有人能指出我正确的方向吗? Thanks a lot. 非常感谢。
I found the answer here Parse String to Date with Different Format in Java , modified the date formats as per your need 我在这里找到了答案,用Java用不同的格式将字符串解析为日期,并根据需要修改了日期格式
MMMM
for complete month in String
MMMM
中完整月份的String
SimpleDateFormat fromUser = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("MMMM dd, yyyy");
try {
String reformattedStr = myFormat.format(fromUser.parse(inputString));
} catch (ParseException e) {
e.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.