问题
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
回答1:
Try this :-
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSS");
Also read this. Hope it will help you.
回答2:
You should use HH instead of hh:
SimpleDateFormat now = new SimpleDateFormat("HH:mm:ss");
回答3:
Time Zone
The question and answers ignore the issue of time zones. Usually it is best to do logging in UTC (no time zone offset) to avoid ambiguity and to avoid confusion over Daylight Saving Time.
ISO 8601
The sensible ISO 8601 standard defines a format for textual representation of date-time values. This format is especially useful in logging.
Joda-Time
The Joda-Time library supports time zones, has a built-in constant for UTC time zone, and uses the ISO 8601 format and it's 24-hour clock by default.
String output = DateTime.now( DateTimeZone.UTC ).toString();
来源:https://stackoverflow.com/questions/22230826/24-hour-in-simpledateformat-and-milliseconds-in-java