在Java中使用日期

时间:2012-07-17 14:18:27

标签: java

我需要处理日期,我不知道如何在Java中实现这一点,因为我以前从未这样做过。

我从Excel文件中提取日期,可以使用代表日期的数据格式检索日期。

例如:

  1. 2/1/2010
  2. 2011/5/12
  3. 2011/8/15
  4. 2011/9/1
  5. 2011/9/1
  6. 我的所有代码对问题都非常重要,但我正在设置一个getter / setter方法:

    public Date getDate() {
        return date;
    }
    
    public void setDate(Date date) {
        this.date = date;
    }
    

    所以我的问题是这样,当我从Excel中提取数据的时候:

        temp.setDate((row.getCell(3).getDateCellValue());
    

    我可以设置限制,因此它只从x个月中检索数据。 8,12,et ..从文件中显示的上个月/年,而不是一直回到2010年?如果需要,我可以提供更多细节。

    编辑:这就是我现在所拥有的:

       import java.util.Date;
        Date date;
       date = row.getCell(3).getDateCellValue();
    

    显示:Tue June 01 00:00:00

    我不关心星期二或00:00:00,我只有一个完整的数据列表,我只想显示x个月。

    编辑:我明白了。 :)

3 个答案:

答案 0 :(得分:0)

您必须使用DateFormat.class解析单元格,或使用日历来放置日月年

修改

您还可以使用 Calendar.class

final String[] tabDate = {"2/1/2010", "5/12/2011", "8/15/2011",
                           "9/1/2011", "9/1/2011"};
// Extract field's value
final Calendar c = Calendar.getInstance();

// Parse the list of stringDate
for (final String string : tabDate) {
    System.out.println("Input string: " + string);
    final String[] shortDate = string.split("/");

   // Build Calendar
    c.set(Integer.valueOf(shortDate[2]), Integer.valueOf(shortDate[0]),
        Integer.valueOf(shortDate[1]));

    // Extract date as you like
    System.out.format("%25s  : %d/%d/%d\t%s\n\n", c.getTime(),
        c.get(Calendar.MONTH), c.get(Calendar.DATE),
        c.get(Calendar.YEAR), c.getTimeInMillis());
}

控制台:

Input string: 2/1/2010
Mon Mar 01 09:09:48 CET 2010  : 2/1/2010    1267430988109

Input string: 5/12/2011
Sun Jun 12 09:09:48 CEST 2011  : 5/12/2011  1307862588109

Input string: 8/15/2011
Thu Sep 15 09:09:48 CEST 2011  : 8/15/2011  1316070588109

Input string: 9/1/2011
Sat Oct 01 09:09:48 CEST 2011  : 9/1/2011   1317452988109

Input string: 9/1/2011
Sat Oct 01 09:09:48 CEST 2011  : 9/1/2011   1317452988109

答案 1 :(得分:0)

问题非常模糊,但如果您使用的是Excel,我发现将文件另存为'filename.csv'非常有用。这种格式非常容易使用,它以逗号分隔并且新行下降。如果您定期检查月份,那么很容易确保您只需要向后走x个月。

答案 2 :(得分:0)

首先,您需要使用SimpleDateFormat类相应地解析日期。结果是一个日期对象。

SimpleDateFormat df = new SimpleDateFormat( "M/d/yyyy" );
Date date = df.parse(row.getCell(3).getDateCellValue());

然后:

Calendar cal = Calendar.getInstance();

将返回一个对象ob类型日历,您可以在其中设置日期

cal.setTime(date);

最后,阅读Excel文件的循环可以根据日历对象确定是否应该使用以下日期包含/进一步处理日期:

int month = cal.get(Calendar.MONTH); // e.g. 11 for Nov
int year = cal.get(Calendar.YEAR); // e.g. 2011