Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

24 hour in SimpleDateFormat() and milliseconds in java

I am building a DAQ software and right now I am in the process of creating a log file. I thought of showing the time on each entry. A simple code(that cannot compile) is the following

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class daq(){

    SimpleDateFormat now = new SimpleDateFormat("hh:mm:ss");

    public void go(){
        report.setProperty("INSERT", "["+now.format(new Date())+"] Acquisition Started\n");
    }
    public void init(){
        report.setProperty("INSERT", "["+now.format(new Date())+"] ADC Channel 1: Read Complete\n");
        report.setProperty("INSERT", "["+now.format(new Date())+"] Initialisation Complete\n");
    }
    public void stop(){
        report.setProperty("INSERT", "["+now.format(new Date())+"] Acquisition Stopped\n");
    }

}

A typical result of the above "code" is the following

[06:30:09] Acquisition Started
[06:30:09] ADC Channel 1: Read Complete
[06:30:09] Initialisation Complete
[06:30:13] Acquisition Stopped

I was wondering if there is a way to display the time in 24 hour format(i.e. 18:30:09 instead of 06:30:09)?

Is there also a way to display milliseconds? A format like hh:mm:ss:mils? I tried to use sss instead of ss but I only get a 0 for the first s. An example output is

[21:50:004] Acquisition Started
[21:50:004] ADC Channel 1: Read Complete
[21:50:004] Initialisation Complete
[21:50:013] Acquisition Stopped
like image 483
Thanos Avatar asked Dec 28 '25 17:12

Thanos


2 Answers

Try this :-

SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSS");

Also read this. Hope it will help you.

like image 70
JDGuide Avatar answered Dec 31 '25 05:12

JDGuide


You should use HH instead of hh:

SimpleDateFormat now = new SimpleDateFormat("HH:mm:ss");
like image 35
Rohit Jain Avatar answered Dec 31 '25 06:12

Rohit Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!