Java日期格式Check

一开始我用下面这个方法来判断日期类型,比如2017/01是否为yyyy/MM格式:

	public static boolean isDate(String strDate, String pattern){

		boolean result = false;
		
		SimpleDateFormat format=new SimpleDateFormat(pattern);
		
		try
		{
			Date date = format.parse(strDate);
			
			result = true;
		}catch (Exception e)
		{
			result=false;
		}
		
		return result;
	}

后来发觉如果输入的是2017/13,2017/0的时候竟然返回true,并且2017/1也可以通过。

后来改成下面这种写法就可以了。

	public static boolean isValidDate(String s,String pattern)
    {
		 SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		 if(s == null || s.trim().equals("")){
		     return true;
		 }
        try
        {
             return sdf.format(sdf.parse(s)).equals(s);
         }
        catch (Exception e)
        {
            return false;
        }
    }


你可以使用Java的POI库来读取Excel日期格式的数据。具体步骤如下: 1. 使用POI库中的Workbook类打开Excel文件。 2. 确定要读取的工作表。 3. 遍历工作表的每一行,读取日期格式的单元格。 4. 使用Java中的日期格式化函数将日期数据转换为标准日期格式。 以下是示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; public class ReadExcelDate { public static void main(String[] args) { try { FileInputStream file = new FileInputStream(new File("your_file.xls")); //Create Workbook instance holding reference to .xlsx file Workbook workbook = WorkbookFactory.create(file); //Get first/desired sheet from the workbook Sheet sheet = workbook.getSheetAt(0); //Iterate through each rows one by one for (Row row : sheet) { //Iterate through each cell one by one for (Cell cell : row) { //Check the cell type and format accordingly switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { System.out.print(cell.getDateCellValue() + "\t"); } else { System.out.print(cell.getNumericCellValue() + "\t"); } break; case Cell.CELL_TYPE_STRING: System.out.print(cell.getStringCellValue() + "\t"); break; } } System.out.println(""); } file.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 该代码将遍历Excel中的每一个单元格,检查其类格式日期数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值