比如做当前积分排行榜,需要获取今天凌晨的时间戳。
万能的 PHP 当然是一句话搞定啦
strtotime(date("Y-m-d 00:00:00", time()));
如果用 Java 呢?自己折腾了半天
public static int getMorningTs(){ SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd"); try { Date date = format.parse(format.format(new Date())); return (int) (date.getTime() /1000); } catch (ParseException e) { e.printStackTrace(); } }
看了下别人的,更好理解
public static int getMorningTs(){ Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.MILLISECOND, 0); return (int) (cal.getTimeInMillis()/1000); }
后台脚本用 php 在脚本统计本周榜单,而前台 api 用 java 输出,出了一点小问题,获取今天星期几上没统一,这里纠正下。还是 API 不熟。
Calendar cal = Calendar.getInstance(); int weekday = cal.get(Calendar.DAY_OF_WEEK); // 1~7 1 表示周日 7 表示周六 if (weekday == 1){ weekday = 8; } weekday = weekday - 1; int weekStartTs = TsUtil.getMorningTs() - (weekday - 1)*86400
date("N", time());// 1~7 1 表示周一 7 表示周日 $weekStartTs = strtotime(date("Y-m-d 00:00:00", time())) - ($weekday - 1)*86400;