编号日期到字日期

时间:2012-10-27 04:31:34

标签: java netbeans

需要帮助,如何在java中转换它? 09-09-2012 = 2012年9月9日? 我们的教练将其作为作业分配..月,日和年,并单独输入

提前thnx

package exam4;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JOptionPane;

public class Exam4 {

public static void main(String[] args) {


        String inMonth=JOptionPane.showInputDialog(null, "Enter Month");
            int intMonth = Integer.parseInt(inMonth);

        String inDay=JOptionPane.showInputDialog(null, "Enter Day");
            int intDay = Integer.parseInt(inDay);

        String inYear=JOptionPane.showInputDialog(null, "Enter Year");
            int intYear = Integer.parseInt(inYear);

        getDate(intMonth, intDay, intYear);


}

static void getDate(int intMonth, int intDay, int intYear){

    if((intMonth==2)&&(intDay<=29)&&(intYear<=9999)){
        JOptionPane.showMessageDialog(null, "February 29, 2012");
        genDate(intMonth,intDay,intYear);
    }         

        else if (((intMonth<12)&&(intDay<31)&&(intYear<9999))&&((intMonth==2)&&(intDay<=29)&&(intYear<=9999))){
            JOptionPane.showMessageDialog(null, "Regular date");

        }

        else{
            JOptionPane.showMessageDialog(null, "atik na date");
        }
}

static void genDate(int intMonth, int intDay, int intYear){

        String fMonth = Integer.toString(intMonth);
        String fDay = Integer.toString(intDay);
        String fYear = Integer.toString(intYear);

        String DateTime=fMonth+fDay+fYear;

    SimpleDateFormat dateFormat = new SimpleDateFormat("MMddyyyy");
    Date myDate = null;

        try {
            myDate = dateFormat.parse(DateTime);
        } catch (ParseException e) {
          }

    SimpleDateFormat timeFormat = new SimpleDateFormat("MMMMM dd, yyyy");
    String finalDate = timeFormat.format(myDate);

    JOptionPane.showMessageDialog(null,finalDate);

} 

}

当我输入02 02 2012时,它给了我奇怪的约会...尝试输入02 29 2012 ..并且它给了12月13日,0013 ..我知道为什么=(

1 个答案:

答案 0 :(得分:3)

使用SimpleDateFormat将字符串转换为日期,然后转换回String,如下所示:

     DateFormat format1 = new SimpleDateFormat("MM-dd-yyyy");
     Date date = format1.parse("09-09-2012");
     DateFormat format2 = new SimpleDateFormat("MMMMM dd, yyyy");
     String dateString = format2.format(date);
     System.out.println(dateString); //<- prints September 09, 2012