简体   繁体   中英

Parsing long to a Date object with formatting

I'm trying to do a function that will parse a long millesecond value into a Date object with formatting:

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;    
}

The format I plugged into the function is this: " dd-MM-yyyy HH-mm:ss " And still I am getting this result format: " Thu Apr 19 19:51:22 SGT 2012 "

Any ideas why I get this kind of result?

The format is applied only when you output the date (actually it is used to convert the date to string). It will not change the internal representation of the date.

In your case the formattedDate object will not be affected in any way by the format .

A way to see the string representation is like that:

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

This is like the bases of a number. You have many different visualizations of a number like 101(2) or 5(10) , but they have meaning only when displaying the number. Otherwise the value of the number itself does not change when you change the base number.

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

return formatter.format(formattedDate);

You are returning a date object but what you need is a formatted date string returned from the created date object that was created using the milliseconds value.

String dateStr = formatter.format(formattedDate); return dateStr;

你的问题是formatter.format(...)返回一个String ,这是你应该在函数中返回的(你实际上返回了Date实例)

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.

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM