Reputation: 5620
I have my Date of Birth variable which is initially of type int. It is then parsed toString() and parsed to Date with simpleDateFormat.
The only issue is that it keeps returning it's default time including the date.
public Date getDob(){
String format = Integer.toString(this.dob);
try{
date = new SimpleDateFormat("ddMMyyyy").parse(format);
}catch(ParseException e){
return null;
}
return date;
}
Returns: Sat Jan 16 00:00:00 CET 1999 [ I want to remove the bold time ]
Thank you very much for your help!
Solution:
public String getDob(){
Date newDate = new Date(this.dob);
String date = new SimpleDateFormat("E MMM dd").format(newDate);
return date;
}
Upvotes: 0
Views: 112
Reputation: 339382
A java.util.Date object by definition has both a date portion and a time-of-day portion.
Understand that a date-time object is not a String. We create String representations of the date-time value contained within a date-time object, but doing so is generating a fresh String object completely separate from the date-time object.
If you want only a date, without the notion of time-of-day, use the LocalDate class found in both Joda-Time and the new java.time package in Java 8 (inspired by Joda-Time).
By default, Joda-Time uses the ISO 8601 standard formats. If you want Strings in other formats, explore the DateTimeFormat class (a factory of DateTimeFormatters).
Example code in Joda-Time 2.3.
String input = "01021903"; // First of February, 1903.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "ddMMyyyy" );
LocalDate dateOfBirth = formatter.parseLocalDate( input );
String outputStandard = dateOfBirth.toString(); // By default, the ISO 8601 format is used.
String outputCustom = formatter.print( dateOfBirth );
Upvotes: 1
Reputation: 46861
Try this one
Date originalDate = new Date();
long timeInMills = originalDate.getTime();
Date newDate = new Date(timeInMills);
String date = new SimpleDateFormat("E MMM dd").format(newDate);
System.out.println(date);
output:
Wed Apr 30
If you want to store the date in long (in milliseconds) if needed.
For more pattern have a look at SimpleDateFormat
Upvotes: 1
Reputation: 240928
You cannot change toString()
method of Date
class,
what you are doing is you are parsing some String to Date and returning Date instance and trying to print it which internally invokes toString()
of Date
and it has fixed format,
You can use format()
method to convert Date
to String
and print it in whatever format you want
Upvotes: 4