I want to get a formatted Date in Java

前端 未结 5 1667
广开言路
广开言路 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: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

提交回复
热议问题