How can I get the count of milliseconds since midnight for the current?

后端 未结 11 685
生来不讨喜
生来不讨喜 2021-01-30 03:45

Note, I do NOT want millis from epoch. I want the number of milliseconds currently on the clock.

So for example, I have this bit of code.

Date date2 = ne         


        
相关标签:
11条回答
  • 2021-01-30 04:18

    You can use java.util.Calendar class to get time in milliseconds. Example:

    Calendar cal = Calendar.getInstance();
    int milliSec = cal.get(Calendar.MILLISECOND);
    // print milliSec
    
    java.util.Date date = cal.getTime();
    System.out.println("Output: " +  new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss:SSS").format(date));
    
    0 讨论(0)
  • 2021-01-30 04:19
    1. long timeNow = System.currentTimeMillis();
    2. System.out.println(new Date(timeNow));

    Fri Apr 04 14:27:05 PDT 2014

    0 讨论(0)
  • 2021-01-30 04:22
    Calendar.getInstance().get(Calendar.MILLISECOND);
    
    0 讨论(0)
  • 2021-01-30 04:27

    I tried a few ones above but they seem to reset @ 1000

    This one definately works, and should also take year into consideration

    long millisStart = Calendar.getInstance().getTimeInMillis();
    

    and then do the same for end time if needed.

    0 讨论(0)
  • 2021-01-30 04:27

    I did the test using java 8 It wont matter the order the builder always takes 0 milliseconds and the concat between 26 and 33 milliseconds under and iteration of a 1000 concatenation

    Hope it helps try it with your ide

    public void count() {
    
            String result = "";
    
            StringBuilder builder = new StringBuilder();
    
            long millis1 = System.currentTimeMillis(),
                millis2;
    
            for (int i = 0; i < 1000; i++) {
                builder.append("hello world this is the concat vs builder test enjoy");
            }
    
            millis2 = System.currentTimeMillis();
    
            System.out.println("Diff: " + (millis2 - millis1));
    
            millis1 = System.currentTimeMillis();
    
            for (int i = 0; i < 1000; i++) {
                result += "hello world this is the concat vs builder test enjoy";
            }
    
            millis2 = System.currentTimeMillis();
    
            System.out.println("Diff: " + (millis2 - millis1));
        }
    
    0 讨论(0)
提交回复
热议问题