I want to get a formatted Date in Java

前端 未结 5 1602
广开言路
广开言路 2021-01-24 23:48

I want to get a new Date object with a SimpleDateFormat applied to it. I would like to do something like:

SimpleDateFormat myFormat =         


        
相关标签:
5条回答
  • 2021-01-25 00:24

    I think what you are trying to achieve does not make sense.

    A Date object represents time. You can not format it. But, you can get it's string representation in certain format. Like with myFormat.format(today).

    0 讨论(0)
  • 2021-01-25 00:26

    you cannot associate a format to a Date object instead you can only apply the formats while displaying or other activities,,

    Do all processing in the Date object itself and while displaying alone change to the required format,,

    0 讨论(0)
  • 2021-01-25 00:29

    I think you're misunderstanding something here about what the Date object is. Date simply holds the information about a point in time - it doesn't have a format at all. When it comes to the String representation of a Date, this is where formatting comes into play. Only worry about the formatting when you are:

    1. Parsing a String representation into a Date object.
    2. Converting a Date back into String representation to display it in a certain way.
    0 讨论(0)
  • 2021-01-25 00:39

    Your question doesn't make sense. Formatting a date by definition means converting it to a string using a specific format. The Date object can stay as a Date object. It is only at the point where you wish to convert it to a String that you need to do any formatting.

    0 讨论(0)
  • 2021-01-25 00:42

    You are looking at Format and Date wrongly.

    • Date does not contain format. Date is just a class containing date info like date, month, hours, sec etc.
    • SimpleDateFormat is the one which tells you the string representation of Date. But there is no date associated with it.

    So the idea is when you have to display date or have to store date in some string representation, you will use SimpleDateFormat and pass it the date you want string representation for.

    One benefit of doing this way is that, I can use same Date object and can show two different string representations (using two different instances of SimpleDateFormat). And also viceversa, having defined one SimpleDateFormat instance, I can format multiple dates.

    Edit:

    Now if you want to strip some info from the date. Use

    Calendar rightNow = Calendar.getInstance();
    Calendar cal = new GregorianCalendar(
       rightNow.get(YEAR),
       rightNow.get(MONTH),
       rightNow.get(DAY_OF_MONTH));
    Date now = cal.getTime();
    

    There are other good soln like JodaTime

    Ref:

    GregorianCalendar Calendar Joda Time

    0 讨论(0)
提交回复
热议问题