我正试图获取当前时间,例如9时04分15秒。截至目前我一直在使用
long unixTime = System.currentTimeMillis() / 1000L;
Date time=new java.util.Date((long)unixTime*1000);
Calendar cal = Calendar.getInstance();
cal.setTime(time);
int hours = cal.get(Calendar.HOUR_OF_DAY);
int minutes = cal.get(Calendar.MINUTE);
int seconds = cal.get(Calendar.SECOND);
currentTime = (hours+":"+minutes+":"+seconds);
其中9:4:15代替。解决这个问题的最佳方法是什么?
由于
答案 0 :(得分:4)
保持简单: 不需要日历,没有div乘以1000然后再乘以,只需执行:
Date time = new java.util.Date(System.currentTimeMillis());
System.out.println(new SimpleDateFormat("HH:mm:ss").format(time));
将打印
13时04分19秒
添加前导
答案 1 :(得分:3)
Calendar c = Calendar.getInstance();
System.out.println("Current time => "+c.getTime());
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = df.format(c.getTime());
答案 2 :(得分:2)
使用simpledateformat方法
String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
答案 3 :(得分:2)
您可以使用SimpleDateFormat
,例如:
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss");
Calendar calendar = Calendar.getInstance();
System.out.println(dateFormat.format(calendar.getTime()));
答案 4 :(得分:1)
使用下一个代码:
currentTime = new SimpleDateFormat("HH:mm:ss").format(cal.getTime());
答案 5 :(得分:1)
LocalTime.now()
.toString()
9时04分15秒
Java 8& S中内置的大部分java.time功能。 9及更高版本后端移植到Java 6& 7在ThreeTen-BackPort项目中,并在ThreeTenABP项目中进一步适应Android。