
2.8 日期和时间处理
java.util包提供的处理日期和时间的类有SimpleDateFormat、DateFormat、Date以及Calendar。其中,SimpleDateFormat和DateFormat类用来实现日期和时间的格式化,常使用的方法有format(Date date)和parse(String source);Date类主要处理指定格式的时间;Calendar类主要用于年月日类型数据的转换。
在采集数据时,不同网站的时间使用格式可能不同。而不同的时间格式,会为数据存储以及数据处理带来一定的困难。例如,图2.13所示为某汽车论坛中的时间使用格式,包含“yyyy-MM-dd”和“yyyy-MM-dd HH:mm”两种格式;图2.14所示为某新闻网站中的时间使用格式为“yyyy-MM-dd HH:mm:ss”。
针对汽车论坛中的“yyyy-MM-dd”和“yyyy-MM-dd HH:mm”格式,可以统一转化成“yyyy-MM-dd HH:mm:ss”格式,以方便数据存储以及后期数据处理,如程序2-14所示。在程序2-14中,parseStringTime()方法的作用是将字符串类型的时间标准化成指定格式的时间,这里通过调用DateFormat类中的parse()方法和format()方法来实现。

图2.13 某汽车论坛中的时间使用格式

图2.14 某新闻网站中的时间使用格式
程序2-14


图2.15所示为程序2-14的输出结果。

图2.15 格式化时间
另外,采集数据时,通常需要记录每一条数据的采集时间。图2.16所示为采集的汽车销量数据,字段craw_time表示采集每条记录的时间信息。程序2-15给出了获取当前时间的一个通用方法。在该方法中,使用了Date类的无参构造方法创建了一个Date对象,进而获取当前时间。
程序2-15


图2.16 采集的汽车销量数据
再者,一些网站的时间格式为UNIX时间戳(即从1970年1月1日开始经过的秒数)。图2.17所示为国外某艺术品网站,基于浏览器抓包(下一章中讲解),发现该网页的时间格式为UNIX时间戳,如图2.18所示。为将UNIX时间戳转化为指定格式的时间,需要构造一个通用的方法,如程序2-16所示。
程序2-16


图2.17 国外某艺术品网站

图2.18 网页中的UNIX时间戳