Search code examples
javaswingdatetimemilliseconds

How to find Caloculate in miliseconds in java


In my stock management project i want to save the time Product is saved. I want to save it in this format.
date + time(in miliseconds)

So I used this code, which is completely failed I think.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JLabel;

/**
*
* @author Dilini
*/
public class test {

public void Timemill(final JLabel jl) {
    new Thread(new Runnable() {
        public void run() {
            while (true) {
                DateFormat smFormat = new SimpleDateFormat("yyyyMMdd");
                Date date = new Date();
                String smday = smFormat.format(date);
                int itime = Calendar.getInstance().get(Calendar.MILLISECOND);
                jl.setText(smday + String.valueOf(itime));
            }
        }
    }).start();

 }
}


But result brings something like this.
20140530542
I know 2014=year 05=month 30=day. I can understand 542 is may be seconds. But seconds usually with 0-60. And 542 over that range.. I want to clarify what that is. Also I want to output time with more formatted way.. Thank you.


Solution

  • Run this and you will see how you can get all parts of a Date.

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        System.out.println(sdf.format(new Date()));
    

    Then use it as appropriate for your particular case.