I am trying t make a date that comes in like this mm/dd turn into the name of the month and day like it comes in 8/15 i want it to say August, 15
public void printAlphabetical()
{
int month,day;/开发者_如何学JAVA/ i got the month and day from a user previously in my program
String s = String.format("%B, %02d%n",month,day);
Date date = new Date();
date.parse(s);// this does not work
System.out.printf(s);
}
System.out.println( new SimpleDateFormat("MMMM, dd").format(
new SimpleDateFormat("MM/dd").parse("2/24") ) );
mmhh dejavu? nahhh exact duplicate -> here
See Calendar and SimpleDateFormat
You can do something like this,
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date date = (Date)formatter.parse(dateStr + "/2000); // Must use leap year
formatter = new SimpleDateFormat("MMMM, dd");
System.out.println(formatter.format(date));
Take a look at the Java simple date format:
https://docs.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html
String[] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}
System.out.println(months[month - 1] + ", " + day);
2/24 as “February, 24”
So, the starting date has a pattern of M/d
and the final date has a pattern of MMMM, d
?
Use java.text.SimpleDateFormat
wisely. First parse the String
based on the desired pattern into a Date
and then format
the obtained Date
into another String
with the desired pattern.
Basic example:
String datestring1 = "2/24"; // or = month + "/" + day;
Date date = new SimpleDateFormat("M/d").parse(datestring1);
String datestring2 = new SimpleDateFormat("MMMM, d").format(date);
System.out.println(datestring2); // February, 24 (Month name is locale dependent!)
精彩评论