1

我正在尝试做一个函数,它将长毫秒值解析为具有格式的 Date 对象:

public static Date parseDate(long millisec, String format) {
    try {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        Date formattedDate = new Date(millisec);
        formatter.format(formattedDate);
        return formattedDate;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;    
}

我插入函数的格式是这样的:“ dd-MM-yyyy HH-mm:ss”我仍然得到这个结果格式:“ Thu Apr 19 19:51:22 SGT 2012

任何想法为什么我会得到这种结果?

4

7 回答 7

2

该格式仅在您输出日期时应用(实际上它用于将日期转换为字符串)。它不会改变日期的内部表示。

在您的情况下,该formattedDate对象不会以任何方式受到format.

查看字符串表示的一种方法是:

String dateString = formatter.format(formattedDate);
System.out.println(dateString);

这就像一个数字的基础。您对数字有许多不同的可视化,例如101(2)or 5(10),但它们仅在显示数字时才有意义。否则,当您更改基数时,数字本身的值不会改变。

于 2012-04-19T12:15:48.090 回答
1

您正在返回一个日期对象,但您需要的是从使用毫秒值创建的创建日期对象返回的格式化日期字符串。

String dateStr = formatter.format(formattedDate); 返回日期Str;

于 2012-04-19T13:10:37.763 回答
1

您返回您的初始日期...改为:

return formatter.format(formattedDate);
于 2012-04-19T12:15:52.243 回答
0

您的问题是formatter.format(...)返回 a String,这是您应该在函数中返回的内容(您实际上返回了Date实例)

于 2012-04-19T12:13:52.487 回答
0

This line:

formatter.format(formattedDate);

Returns a String (the formatted date). What you return is the Date object (which in itself has no formatting). You should return the String that is returned from the formatter.

于 2012-04-19T12:14:16.487 回答
0

You are returning an object of Date. Date is a abstract representation of a point in time, without any information about formatting. You need to return the String you get from the formatter - that is a formatted representation of time (but on the other hand contains no information about the time - you would have to parse it back to get the Date object it represents).

于 2012-04-19T12:14:46.050 回答
0

A Date has no formatting of its own, it's the SimpleDateFormat that does the formatting.

When you call formatter.format(formattedDate) it's returning you a String which is formatted, but you're ignoring the returned value.

于 2012-04-19T12:14:46.140 回答