使用日期时,如何获取当前时间为09:04:15而不是9:4:15? [英] How can I get current time as 09:04:15 instead of 9:4:15 when using Date?

查看:114
本文介绍了使用日期时,如何获取当前时间为09:04:15而不是9:4:15?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取当前时间,例如09:04:15。到目前为止,我一直在使用

I am trying to get current time as e.g. 09:04:15. As of now I have been using

    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。解决此问题的最佳方法是什么?

Which gives 9:4:15 instead. What is the best way to solve this?

谢谢

推荐答案

您可以使用 SimpleDateFormat ,例如:

SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss");
Calendar calendar = Calendar.getInstance();
System.out.println(dateFormat.format(calendar.getTime()));

这篇关于使用日期时,如何获取当前时间为09:04:15而不是9:4:15?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆