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

2019-06-13 18:23发布

问题:

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

回答1:

You can use SimpleDateFormat, e.g.:

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


回答2:

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



回答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());


回答4:

Use simpledateformat method

String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());


回答5:

Use next code:

currentTime = new SimpleDateFormat("HH:mm:ss").format(cal.getTime());


回答6:

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.