24 hour in SimpleDateFormat() and milliseconds in java

三世轮回 提交于 2019-12-13 14:15:14

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!