今天贴吧有个帖子说:周五到了周末还会远吗。。
看到这里便想写段代码来计算一下到周末的时间差。
- 实现语言:Java
- 环境:jdk1.8.0_102
- 时间:2016年11月25日12:16:58
- 代码
/**
* JavaSE8提供了强大的日期处理API,因此使用这些API很方便
*/
public static void main(String[] args) {
//获得当前时间戳
final LocalDateTime rightNowOrigin = LocalDateTime.now();
//获得周六的时间戳 ,方法参数:年份,月份(枚举),该月的哪一天,时,分,秒
final LocalDateTime saturdayTime = LocalDateTime.of(2016, Month.NOVEMBER, 26, 0, 0, 0);
//获得周日的时间戳,方法参数同上,这个方法是一个重载方法,其它方法还可以指定纳秒
final LocalDateTime sundayTime = LocalDateTime.of(2016, Month.NOVEMBER, 27, 0, 0, 0);
//指定时期的格式
final String formatPattern = "yyyy-MM-dd HH:mm:ss";
//格式化时间戳
final String rightNowFormatted = rightNowOrigin
.format(DateTimeFormatter.ofPattern(formatPattern, Locale.CHINESE));
//同上
final String saturdayTimeFormatted = saturdayTime
.format(DateTimeFormatter.ofPattern(formatPattern, Locale.CHINESE));
//同上
final String sundayTimeFormatted = sundayTime
.format(DateTimeFormatter.ofPattern(formatPattern, Locale.CHINESE));
//计算当前时间戳和指定时间戳时间间隔
final long intervalsForSatu = ChronoUnit.SECONDS.between(rightNowOrigin, saturdayTime);
//计算方法还有 LocalDateTime的实例方法 :until(Temporal endExclusive, TemporalUnit unit)
//据API文档描述,这两个方式作用效果是一样的。
final long intervalsForSun = ChronoUnit.SECONDS.between(rightNowOrigin, sundayTime);
System.out.println("此楼时间:" + rightNowFormatted);
System.out.println("周六时间:" + saturdayTimeFormatted);
System.out.println("周日时间:" + sundayTimeFormatted);
System.out.println("距周六还剩下: " + intervalsForSatu + " 秒");
System.out.println("距周日还剩下:" + intervalsForSun+ " 秒");
}
运行结果
此楼时间:2016-11-25 12:16:58
周六时间:2016-11-26 00:00:00
周日时间:2016-11-27 00:00:00
距周六还剩下: 42181 秒
距周日还剩下:128581 秒总结
日常生活中有很多小事情是可以靠编程来解决的,并不是只有在业务需求时才动手写代码~
遇到不熟悉的API一定要去查官方文档(附上JavaSE8官方文档链接:http://docs.oracle.com/javase/8/docs/api/),盲目的360搜索、Google、百度的话如果碰到出现过类似需求的人还好,碰不到那就是浪费时间了。
happy coding~ O(∩_∩)O~