timestamp有两个属性,分别是CURRENT_TIMESTAMP 和ON UPDATE CURRENT_TIMESTAMP两种,使用情况分别如下:
1.CURRENT_TIMESTAMP
当要向数据库执行insert操作时,如果有个timestamp字段属性设为
CURRENT_TIMESTAMP,则无论这个字段有木有set值都插入当前系统时间
2.ON UPDATE CURRENT_TIMESTAMP
当执行update操作是,并且字段有ON UPDATE CURRENT_TIMESTAMP属性。则字段无论值有没有变化,他的值也会跟着更新为当前UPDATE操作时的时间。
1.时间戳转Date
public static voidmain(String[] args) {//10位的秒级别的时间戳
long time1 = 1527767665;
String result1= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time1 * 1000));
System.out.println("10位数的时间戳(秒)--->Date:" +result1);
Date date1= new Date(time1*1000); //对应的就是时间戳对应的Date//13位的秒级别的时间戳
double time2 =1515730332000d;
String result2= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time2);
System.out.println("13位数的时间戳(毫秒)--->Date:" +result2);
}
10位数的时间戳(秒)--->Date:2018-05-31 19:54:2513位数的时间戳(毫秒)--->Date:2018-01-12 12:12:12
2. 判断两个时间点时候为同一天,同一年
给定两个日期,快速判断两者是否为同一天或者同一年,比如我做过的一个接口需求是:每人每天有一次抽奖机会,那么当用户当天第二次发送请求时候,我就得判断查询参与记录,并且判断最新一次参与时间和当天是否为同一天。
/*** 判断是否为同一天:使用commons-lang包下的DateUtils类
*
*@paramday1
*@paramday2
*@return
*/
public booleanisSameDay(Date day1, Date day2) {returnDateUtils.isSameDay(day1, day2);
}/*** 判断是否为同一天:使用joda依赖包里的时间类,效率从一定程度上优于DateUtils.isSameDay()方法
*
*@paramdate1
*@paramdate2
*@return
*/
public static booleanisSameDay1(Date date1,Date date2){if(date1==null || date2==null){throw new IllegalArgumentException("date must be not null");
}
LocalDate localDate1= new LocalDate(newDateTime(date1.getTime()));
LocalDate localDate2= new LocalDate(newDateTime(date2.getTime()));returnlocalDate1.equals(localDate2);
}
/**
* 格式化输出
*/
public static String messageFormat(String pattern, Object[] arr) {
if (pattern == null || arr == null) {
return "";
}
return new MessageFormat(pattern).format(arr);
}