转换上次修改日期时出错

时间:2017-04-11 02:47:26

标签: java

我正在研究一个程序,该程序告诉文件的最后修改日期是否在日期的范围内,从日期到日期,如果它在范围内,它将复制,但我有错误

      File src = new File(sourcefile + File.separator + strErrorFile[i]);
    if(sourcefile.isDirectory())
    {
        ArrayList<Integer> alDateList = date(strList1);
        int intDateFrom1 = alDateList.get(0);
        int intDateTo1 = alDateList.get(1);
         SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        System.out.println("After Format : " + sdf.format(src.lastModified()));
    try
    {
        lastDate = Integer.parseInt(sdf.format(src.lastModified())); //line 362
        } catch (NumberFormatException e) {
          e.printStackTrace();
    }
        if(intDateFrom1 <= lastDate && intDateTo1 >= lastDate)
    {
             //copy
    }
    }

错误

java.lang.NumberFormatException: For input string: "09/10/2015"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at org.eclipse.wb.swt.FortryApplication$4.widgetSelected(FortryApplication.java:362)
at org.eclipse.swt.widgets.TypedListener.handleEvent(Unknown Source)
at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source)
at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source)
at org.eclipse.wb.swt.FortryApplication.open(FortryApplication.java:56)
at org.eclipse.wb.swt.FortryApplication.main(FortryApplication.java:610)

2 个答案:

答案 0 :(得分:2)

您需要退后一步,看看您需要什么以及拥有什么。

您不希望将lastModified值转换为String(通过DateFormatter),因为它不会给您带来任何实际价值,而不是您认为有一整套专用于处理日期/时间的API

让我们先来看看File#lastModified

JavaDocs声明它返回:

  

表示文件上次修改时间的长值,以纪元(1970年1月1日格林威治标准时间00:00:00)为单位测量,如果文件不存在或I / O错误,则为0L发生

好的,这实际上很好,因为您可以使用此值生成LocalDateTime对象...

LocalDateTime ldt = LocalDateTime.ofInstant(new Date(src.lastModified()).toInstant(), ZoneId.systemDefault());

你为什么要这样做?因为LocalDateTime具有可以轻松与其他LocalDateTime对象进行比较的方法......

    LocalDateTime from = ...;
    LocalDateTime to = ...;

    if (ldt.isAfter(from) && ldt.isBefore(to)) {
        //between...
    }

您还可以使用LocalDateTime#equals来比较两个日期是否相等。

如果你不需要&#34;时间&#34;组件,您可以使用LocalDateTime#toLocalDate来获取基于日期(没有时间)的对象,但比较过程基本相同

您可以查看this answer,其中包含确定日期/时间值是否介于两个给定日期/时间值之间的总体逻辑

答案 1 :(得分:1)

  

java.lang.NumberFormatException:对于输入字符串:&#34; 09/10 / 2015&#34;

这不是有效的整数,因此是错误。

您可以采用的一种方法是使用 String.replaceAll() 方法将/的每个实例替换为空字符串"",这应该基本上留给我们与09102015

note - 当您将此解析为整数时,前导零(0)将被删除。

示例:

String data = sdf.format(src.lastModified());

然后你可以这样做:

lastDate = Integer.parseInt(data.replaceAll("/",""));
相关问题