I want to get a new Date
object with a SimpleDateFormat
applied to it. I would like to do something like:
SimpleDateFormat myFormat =
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)
.
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,,
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:
String
representation into a Date
object.Date
back into String
representation to display it in a certain way. 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.
You are looking at Format and Date wrongly.
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