英文:
Get the Month from a date string
问题
我有一个日期字符串输入,如"10/10/2020"(假设它们总是以/分隔),我正在尝试将每个部分存储在已定义为Month、Day和Year的私有int变量中。
我使用了parseInt、indexOf和substring方法来找到月份并将其存储在月份变量中,但是我很难弄清楚如何让程序读取日期。我们假设月份和日期可以是"00"或"0"格式。
这是我从字符串中读取月份的方式,这是我目前为止读取日期的代码,但是我遇到了错误。
java.lang.StringIndexOutOfBoundsException: begin 2, end 0, length 8
这是我的代码,请告诉我我的错误在哪里。
int firstSlash = date.indexOf("/");
int secondSlash = date.indexOf("/", firstSlash);
month = Integer.parseInt(date.substring(0, firstSlash));
day = Integer.parseInt(date.substring(firstSlash + 1, secondSlash - 1));
英文:
I have a String input of date "10/10/2020" (assume they are always going to be separated with /) and I am trying to store each category in a private int variable already defined as Month, Day, and year.
I used the parseInt, indexOf, and substring methods to find the month and store it in the month variable but I am having a hard time figuring out how I can have the program read the day. We are to assume that the month and day can be in "00" or "0" formats.
This is how I am reading the month from the string and this is what I got so far for reading the day but I am getting an error.
> java.lang.StringIndexOutOfBoundsException: begin 2, end 0, length 8
This is my code so far please let me know what mistake I am doing.
int firstSlash = date.indexOf("/");
int secondSlash = date.indexOf("/", firstSlash);
month = Integer.parseInt (date.substring (0, firstSlash));
day = Integer.parseInt (date.substring(firstSlash+1, secondSlash-1));
I don't want the answer but please help me understand the logic of where I am going wrong because based on my understanding I seem to be getting the Index values between the first and second slash and converting the String value into an int.
答案1
得分: 2
- 首先,您需要从第一个找到的斜杠
/
的下一个索引开始搜索,这意味着在date.indexOf(""/"", firstSlash)
中,应该使用firstSlash + 1
而不是firstSlash
。 .substring()
的第二个参数是不包含的,因此在date.substring(firstSlash+1, secondSlash-1)
中,您需要使用secondSlash
而不是secondSlash-1
。
您的代码应如下所示:
String date = "10/10/2020";
int firstSlash = date.indexOf(""/"");
int secondSlash = date.indexOf(""/"", firstSlash + 1);
int month = Integer.parseInt(date.substring(0, firstSlash));
int day = Integer.parseInt(date.substring(firstSlash + 1, secondSlash));
最好使用 LocalDate
来存储日期,并使用 DateTimeFormatter
来解析日期。
英文:
- First you need to search from next index of first
/
found means you should usefirstSlash + 1
insteadfirstSlash
indate.indexOf("/",
.
firstSlash) .substring()
's 2nd paramerter is exclusive, so you need to usesecondSlash
instead ofsecondSlash-1
indate.substring(firstSlash+1, secondSlash-1)
.
Your code should be like
String date = "10/10/2020";
int firstSlash = date.indexOf("/");
int secondSlash = date.indexOf("/", firstSlash + 1);
int month = Integer.parseInt (date.substring (0, firstSlash));
int day = Integer.parseInt (date.substring(firstSlash+1, secondSlash));
It's better to use LocalDate
to store date and use DateTimeFormatter
to parse the date.
答案2
得分: 1
以下是翻译好的内容:
我不想要答案,但请帮我理解我的逻辑错误在哪里,因为...
这就是我和我们喜欢的态度,一个真正学习者的态度。我会提供有用的信息和链接,而不是为你解决错误。
- 与其他人一样,我建议你在日期处理中使用现代的 java 日期和时间 API,即 java.time。
- 你的代码中似乎存在一些索引不准确的问题。
java.time
使用 java.time 的 LocalDate
类表示日期,使用其 getMonth
或 getMonthValue
方法获取月份。java.time 可以解析日期字符串,其中月份和日期可以采用 "00" 或 "0" 的格式。如果你尝试并有疑问,随时欢迎你提一个新的问题。
你的代码出了什么问题
以下内容足以识别你代码中的缺陷:
- 首先,我认为你已经很了解:Java 中的索引是从 0 开始的。
String.indexOf(String, int)
的两个参数版本从给定的索引 包含在内 开始搜索字符串。如果要搜索的子字符串在你指定的索引处,将返回相同的索引。substring(int, int)
的两个参数版本会给你从起始索引 包含在内 到结束索引 排除在外 的子字符串。结束索引必须至少大于等于起始索引,否则将抛出StringIndexOutOfBoundsException
。异常消息会提到你传递给substring()
的两个索引,这可能让你有机会回想起它们从哪里来。
预留
我知道我来晚了。我仍然忍不住发布我认为是一个很好的答案。
链接
- 对于 java.time
- Oracle 教程:日期时间
LocalDate.getMonth()
的文档DateTimeFormatter
的文档- 一个关于解析带有可能是一位或两位数字的日期的相关问题:是否有主日期时间模式适用于每个类似日期时间模式
- 对于字符串索引
英文:
> I don't want the answer but please help me understand the logic of
> where I am going wrong because …
That's the attitude I and we like, the attitude of a true learner. I will provide useful information and links, not solve your error for you.
- Like others I recommend that you use java.time, the modern java date and time API, for your date work.
- You sem to have some indexing inaccuracies in your code.
java.time
Use the LocalDate
class of java.time for a date and its getMonth
or getMonthValue
method for getting the month. java.time can parse a date string where month and day can be in "00" or "0" formats. If you try it and run into doubts, a new question from you is always welcome.
What went wrong in your code
This should suffice for identifying the flaws in your code:
- To start with what I think you already know well: indices in Java are 0-based.
- The two-argument
String.indexOf(String, int)
searches the string from the given index inclusive. If the substring searched for is at the index you specify, the same index is returned. - The two-argument
substring(int, int)
gives you the substring from the from-index inclusive to the to-index exclusive. The to-index needs to be at least as great as the from-index, or aStringIndexOutOfBoundsException
will be thrown. The exception message mentions the two indices that you passed tosubstring()
, which may give you a chance to think backward to where they came from.
Reservation
I know I'm late at the party. I still couldn't resist posting what I think is a good answer.
Links
- For java.time
- Oracle tutorial: date time
- Documentation of
LocalDate.getMonth()
- Documentation of
DateTimeFormatter
- A related question on parsing dates with numbers that may be one or two digits: is there master date time pattern which will work for every similar date time patterns
- For string indexing
答案3
得分: 0
以下是翻译好的内容:
// 导入必要的类
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String strDate = "10/10/2020";
LocalDate date = LocalDate.parse(strDate, DateTimeFormatter.ofPattern("M/d/u"));
int year = date.getYear();
int month = date.getMonthValue();
int dayOfMonth = date.getDayOfMonth();
System.out.println("年份:" + year + ",月份:" + month + ",日期:" + dayOfMonth);
}
}
输出结果:
年份:2020,月份:10,日期:10
了解更多现代日期时间 API,请参阅 **[教程:日期时间](https://docs.oracle.com/javase/tutorial/datetime/index.html)**。
[1]: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html
[2]: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
英文:
The idiomatic way of doing it is by using the date-time API e.g. LocalDate
and DateTimeFormatter
as shown below:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String strDate = "10/10/2020";
LocalDate date = LocalDate.parse(strDate, DateTimeFormatter.ofPattern("M/d/u"));
int year = date.getYear();
int month = date.getMonthValue();
int dayOfMonth = date.getDayOfMonth();
System.out.println("Year: " + year + ", Month: " + month + ", Day of month: " + dayOfMonth);
}
}
Output:
Year: 2020, Month: 10, Day of month: 10
Learn more about the modern date-time API at Trail: Date Time.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论