0

我需要将表示日期的字符串转换为日期。

日期构造如下:

private int m;
private int d;
private int y;

public Date(int month, int day, int year) {
      if (isValidDate(month, day, year)) {
          m = month;
          d = day;
          y = year;  
      } else {
          System.out.println("Error: not a valid date");
          System.exit(0);
      }
  }

需要转换为该日期对象的字符串格式为:

"month/day/year"

月份为 1 或 2 个字符,日为 1 或 2 个字符,年份可以为 1 - 4 个字符。

我的想法是遍历字符串并找到字符/出现的时间,但我觉得有更好的方法来处理它。

实现这一目标的最佳方法是什么?

4

4 回答 4

1

你可以这样做:

String date = "14/02/2013";
String [] splitDate = date.split("/");
Date date = new Date(Integer.parseInt(splitDate[0]),
                     Integer.parseInt(splitDate[1]),
                     Integer.parseInt(splitDate[2]));
于 2013-02-14T00:51:02.000 回答
0

使用`String.split("/")

它为每个标记返回字符串数组,然后您只需将每个标记解析为整数并创建日期对象。`

您可能还想查看 DateFormat 类。它可能能够为您解析字符串。

编辑:

而是使用静态工厂方法。

public static Date asDate(String s) { 
    String[] dateStrings = s.split("/"); 
    int m = Integer.parseInt(dateStrings[0]); 
    int d = Integer.parseInt(dateStrings[1]); 
    int y = Integer.parseInt(dateStrings[2]); 
    return new Date(m, d, y);
}
于 2013-02-14T00:45:48.517 回答
0

也许这段代码可以帮助你。

public class TestDate {

    private int m;
    private int d;
    private int y;

    public static void main(String[] args) {
        String date = "02/14/2013";
        String[] splitDate = date.split("/");
        TestDate td = new TestDate();
        td.Date(Integer.parseInt(splitDate[0]),
                Integer.parseInt(splitDate[1]), 
                Integer.parseInt(splitDate[2]));
        System.out.println(td.m +"/"+td.d+ "/"+td.y);
    }

    public void Date(int month, int day, int year) {
        if (isValidDate(month, day, year)) {
            m = month;
            d = day;
            y = year;
        } else {
            System.out.println("Error: not a valid date");
            System.exit(0);
        }
    }

    private static boolean isValidDate(int month, int day, int year) {
        String stDate = month + "/" + day + "/" + year;
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        sdf.setLenient(false);
        try {
            sdf.parse(stDate);
            return true;
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
    }
}
于 2013-02-14T01:10:43.503 回答
-1

也许您可以使用字符串类的方法来获取您的子字符串,或者使用某种字符串标记器(我不太了解 java,所以无法帮助您提供确切的名称)。但是“在幕后”这些函数也必须遍历字符串,没有办法绕过它。所以我认为你的想法很好。这只是您是否想掌握 Java 中内置的可能性的问题,或者您只是想快速完成它:)

于 2013-02-14T00:51:38.323 回答