How can I get current time as 09:04:15 instead of

2019-06-13 17:50发布

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);

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

Thanks

6条回答
戒情不戒烟
2楼-- · 2019-06-13 18:03

java.time

LocalTime.now()
         .toString()

09:04:15

Much of the java.time functionality built into Java 8 & 9 and later is back-ported to Java 6 & 7 in the ThreeTen-BackPort project and further adapted to Android in the ThreeTenABP project.

查看更多
The star\"
3楼-- · 2019-06-13 18:07

Use next code:

currentTime = new SimpleDateFormat("HH:mm:ss").format(cal.getTime());
查看更多
欢心
4楼-- · 2019-06-13 18:09

Keep it simple: No calendar required, no div by 1000 and then multiply again, just do:

Date time = new java.util.Date(System.currentTimeMillis());
System.out.println(new SimpleDateFormat("HH:mm:ss").format(time));

will print

13:04:19

adding leading zeros

查看更多
何必那么认真
5楼-- · 2019-06-13 18:24
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());
查看更多
forever°为你锁心
6楼-- · 2019-06-13 18:26

You can use SimpleDateFormat, e.g.:

SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss");
Calendar calendar = Calendar.getInstance();
System.out.println(dateFormat.format(calendar.getTime()));
查看更多
家丑人穷心不美
7楼-- · 2019-06-13 18:30

Use simpledateformat method

String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
查看更多
登录 后发表回答