package com.walker.infrastructure.utils; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import com.walker.infrastructure.utils.StringUtils; /** * 日期对象自定义。

* 该对象用来区分:年、月、日响应的值,在很多情况下我们需要知道其中单独的值。
* 通过构造函数输入时间字符串,如:2015-11-30 18:50:44,来解析。

* 已废弃,移动到waler-infrastructure.jar中。 * @author shikeying * @date 2016年5月3日 * */ public class DateObject { private static final DateFormat whippletreeTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private static final String MIDDLE_LINE = "-"; private int year = 0; private int month = 0; private int day = 0; private int dateValue = 0; // 日期值,如:20160503 private int yearDate = 0; // 年日期,如:201605 /** * 返回年月,如:201605 * @return */ public int getYearDate() { return yearDate; } public int getYear() { return year; } public int getMonth() { return month; } public int getDay() { return day; } /** * 返回日期6位数值,如:20181225 * @return */ public int getDateValue() { return dateValue; } /** * 创建日期对象 * @param timestamp 输入日期字符串,如:2015-11-30 18:50:44 */ public DateObject(String timestamp){ if(StringUtils.isEmpty(timestamp)){ throw new IllegalArgumentException("接收到时间数据不存在(timestamp is null)"); } this.dateValue = Integer.parseInt(timestamp.substring(0, 10) .replaceAll(MIDDLE_LINE, StringUtils.EMPTY_STRING)); this.year = dateValue / 10000; this.month = dateValue / 100 - this.year * 100; this.yearDate = dateValue / 100; this.day = dateValue % yearDate; } /** * 使用当前时间作为输入日期 */ public DateObject(){ this(whippletreeTimeFormat.format(new Date(System.currentTimeMillis()))); } /** * 构造函数输入日期数值,转换为日期对象 * @param dateValue 日期数值,如:20181225 */ public DateObject(int dateValue){ if(dateValue <= 0){ throw new IllegalArgumentException("dateValue must >= 0, eg. 20181225"); } this.dateValue = dateValue; this.year = dateValue / 10000; this.month = dateValue / 100 - this.year * 100; this.yearDate = dateValue / 100; this.day = dateValue % yearDate; } @Override public String toString(){ return new StringBuilder().append("[ year=").append(year) .append(", month=").append(month) .append(", day=").append(day) .append(", dateValue=").append(this.dateValue) .append(", yearDate=").append(this.yearDate) .append("]").toString(); } public static void main(String[] args){ // int dateValue = 20160503; // System.out.println(dateValue / 100); // int dateValue = 20160430; // System.out.println("year = " + dateValue / 10000); // System.out.println("month = " + dateValue / 100); // System.out.println("day = " + dateValue % (dateValue / 100)); /** DateObject obj = new DateObject(); System.out.println(obj); String[] datas = new String[]{"2015-11-30 18:50:44" , "2016-04-30 18:50:44" , "2016-05-03 01:23:01" , "2016-05-04 01:23:01" , "2016-12-31 12:59:00" }; for(int i=0; i