JAVA Current date and time
2015-09-22 20:02
537 查看
项目要求
Invoking System.currentTimeMillis() returns the elapse time in milliseconds since midnight of January 1,1970.Write a program that displays the date and time.Here is a sample run:Current date and time is May 16, 2009 10:34:23
代码如下
public class CurrentTime { public static void main(String[] args) { long currentSec = (long) (System.currentTimeMillis() / 1000);// 将毫秒/1000转换为秒 long lastSec = 0;// 剩余秒数 long yearSec = 31536000;// 365*24*60*60,即一年的秒数 long oneDaySec = 86400;// 24*60*60,即一天的秒数 long hourSec = 3600;// 60*60,即一小时的秒数 int[] day = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int year, month; for (year = 1970; currentSec - lastSec >= yearSec; year++) { lastSec += yearSec; if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { lastSec += oneDaySec;// 闰年多一天 } } if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { day[2] = 29; } else day[2] = 28; for (month = 0; currentSec - lastSec >= oneDaySec * 28; month++) { lastSec += day[month] * oneDaySec;// 计算出月份 } String monthS;// 将月份转为英文 switch (month) { case 1: monthS = "Jan"; break; case 2: monthS = "Feb"; break; case 3: monthS = "Mar"; break; case 4: monthS = "Apr"; break; case 5: monthS = "May"; break; case 6: monthS = "Jun"; break; case 7: monthS = "Jul"; break; case 8: monthS = "Aug"; break; case 9: monthS = "Sep"; break; case 10: monthS = "Oct"; break; case 11: monthS = "Nov"; break; case 12: monthS = "Dec"; break; default: monthS = "error!"; break; } long last = currentSec - lastSec;// 用last记录每次计算时分秒后的剩余秒数 long date = last / oneDaySec; last -= date * oneDaySec; long hour = last / hourSec; last -= hour * hourSec; long minute = last / 60; last -= minute * 60; long second = last; System.out.print("Current date and time is " + monthS + " " + date + ", " + year + " " + hour + ":" + minute + ":" + second); System.out.printf( "\nCurrent date and time is %s %d, %2d %02d:%02d:%02d", monthS, date, year, hour, minute, second); // 用printf标准化格式 } }
运行结果
Current date and time is Sep 21, 2015 11:57:0 Current date and time is Sep 21, 2015 11:57:00
学习心得
还是蛮有成就感的…研究printf的格式也是研究了半天,以前学C++没有用过,感觉还是很好用的%02d即保证两位数,位数不足用0占位,从运行结果可以看出标准化格式前后区别
题目来自《JAVA语言程序设计》P196 5.33***
相关文章推荐
- JAVA上机作业 3.22
- SpringMVC设置缺省的返回数据格式
- 关于springMVC访问静态文件404
- Java教程开山篇—开发环境搭建
- eclipse安装ADT插件后,eclipse选项面板无android相关按钮显示问题解决
- java格式化输出 printf 例子
- JAVA Game: learning addition
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- 关于Map还有List,然后还是Map,已经晕倒的逻辑。新手照搬。。。。。三个月了,还是新手,真是惭愧。
- JAVA上机作业 3.4
- ubuntu 14.04 hadoop eclipse 0配置基本环境
- JAVA上机——3.4
- 韩顺平java 第14讲第15讲 作业评讲
- 在JAVA中封装JSONUtils工具类及使用
- JAVA正则表达式 Pattern和Matcher
- java的构造函数
- Stub方式接口化封装axis2 webservice:实现衍生对象与原始对象的相互转换
- 大龄屌丝自学笔记--Java零基础到菜鸟--022
- struts2开发-validate-表单验证案例1
- myEclipse Could not create the view: An unexpected exception was thrown.