how would you write te date if i have a date and all i want is the month and the day like this (mm/dd) and then turn the month like this July, 08
Use:
Format formatter = new SimpleDateFormat("MMMM, dd");
String s = formatter.format(date);
Formatting a Date Using a Custom Format
the month and the day like this (mm/dd) and then turn the month like this July, 08
So you want to convert MM/dd
to MMMM, dd
? So you start with a String
and you end up with a String
? Then you need another SimpleDateFormat
instance with the first pattern.
String dateString1 = "07/08";
Date date = new SimpleDateFormat("MM/dd").parse(dateString1);
String dateString2 = new SimpleDateFormat("MMMM, dd").format(date);
System.out.println(dateString2); // July, 08 (monthname depends on locale!).
Let me see if I understood well.
You have a date like "07/08" and you want "July, 08"?
You could try SimpleDateFormat
import java.text.SimpleDateFormat;
import java.text.ParseException;
class Test {
public static void main( String [] args ) throws ParseException {
SimpleDateFormat in = new SimpleDateFormat("MM/dd");
SimpleDateFormat out = new SimpleDateFormat("MMMM, dd");
System.out.println( out.format( in.parse("07/08") ) );
// Verbose
//String input = "07/09";
//Date date = in.parse( input );
//String output = out.format( date );
//System.out.println( output );
}
}
The SimpleDateFormat is your friend here. If you already have a java.util.Date
object, just format it using the desired pattern (refer to the javadoc for details on date and time patterns):
SimpleDateFormat out = new SimpleDateFormat("MMMM, dd");
String s = out.format(date); // date is your existing Date object here
(EDIT: I'm adding some details as the original question is unclear and I may have missed the real goal.
If you have a String
representation of a date in a given format (e.g. MM/dd) and want to transform the representation, you'll need 2 SimpleDateFormat
as pointed out by others: one to parse the String
into a Date
and another one to format the Date
.
SimpleDateFormat in = new SimpleDateFormat("MM/dd");
Date date = in.parse(dateAsString); // dateAsString is your String representation here
Then use the code snippet seen above to format it.)