开发者

Why does java not convert my time correctly?

I have the following method to convert a String to Date object

public Date convertTime(String time) {

    SimpleDateFormat parser = new SimpleDateFormat("d/M/y HH:mm:ss.S");
    try {
        return parser.parse(time);
    }
    catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }


}

I have t开发者_开发问答he following method to convert it back

public String dateToTimeMillis(Date date) {

    //StringBuffer formatted = new StringBuffer();
    SimpleDateFormat parser = new SimpleDateFormat("HH:mm:ss.S");
    try {
        String formatted = parser.format(date);
        return formatted;
    }
    catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }


}

The following test code

    TraderLib lib = new TraderLib();
    Date d1 = lib.convertTime("01/11/2011 10:41:09.045");
    System.out.println(lib.dateToTimeMillis(d1));

returns 10:41:09.45

How do I preserve the 0?


You should set the format to:

new SimpleDateFormat("d/M/y HH:mm:ss.SSS");

to preserve 3 digits. From the documentation:

"Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields."


Use SimpleDateFormat parser = new SimpleDateFormat("d/M/y HH:mm:ss.SSS");

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜