微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从日期字符串获取月份

如何解决从日期字符串获取月份

我有一个日期为“ 10/10/2020”的字符串输入(假设它们总是用/分隔),并且我试图将每个类别存储在一个已经定义为Month,Day和年。

我使用parseInt,indexOf和substring方法找到月份并将其存储在month变量中,但是我很难弄清楚如何让程序读取日期。我们假设月份和日期可以采用“ 00”或“ 0”格式。

这是我从字符串中读取月份的方式,这是到目前为止读取日期的方式,但是出现错误

java.lang.Stringindexoutofboundsexception:开始2,结束0,长度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));
    

我不想要答案,但是请帮助我理解我要去哪里的逻辑,因为根据我的理解,我似乎在第一个斜杠和第二个斜杠之间获取了Index值,并将String值转换为int

解决方法

  • 首先,您需要从找到的第一个/的下一个索引中进行搜索,这意味着您应该使用firstSlash + 1中的firstSlash而不是date.indexOf("/",firstSlash)
  • .substring()的第二个参数是互斥的,因此您需要使用secondSlash代替secondSlash-1中的date.substring(firstSlash+1,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解析日期。

,

我不想要答案,但是请帮助我理解 我要去哪里错了,因为...

这就是我和我们喜欢的态度,一个真正的学习者的态度。我将提供有用的信息和链接,而不是为您解决错误。

  1. 与其他人一样,我建议您使用java.time(现代的Java日期和时间API)进行日期工作。
  2. 您似乎在代码中存在一些索引错误。

java.time

使用java.time的LocalDate类获取日期,并使用其getMonthgetMonthValue方法获取月份。 java.time可以解析日期字符串,其中月份和日期可以采用“ 00”或“ 0”格式。如果您尝试并遇到疑问,总是欢迎您提出新的问题。

您的代码出了什么问题

这足以识别代码中的缺陷:

  1. 首先,我认为您已经很了解:Java的索引基于0。
  2. 两个参数String.indexOf(String,int)从给定索引包含中搜索字符串。如果搜索的子​​字符串在您指定的索引处,则返回相同的索引。
  3. 两个参数substring(int,int)为您提供从起始索引到目标索引排他的子字符串。 to-index必须至少与from-index一样大,否则将抛出StringIndexOutOfBoundsException。异常消息中提到了您传递给substring()的两个索引,这可能使您有机会反省它们的来源。

预订

我知道我晚会很晚。我仍然忍不住发表我认为是一个好的答案。

链接

,

惯用的方法是使用日期时间API,例如LocalDateDateTimeFormatter如下所示:

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);
    }
}

输出:

Year: 2020,Month: 10,Day of month: 10

通过 Trail: Date Time 了解有关现代日期时间API的更多信息。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。