在下面的代碼 輸入:爪哇日期轉換
Enter Date: 3/2/2011
輸出:
Entered Date is February 3, 2011
Entered Month is 02
問題是,當我輸入這個日期3/14/2012
,日期格式功能自動更改一個月12+2
(2月)。如果我輸入13/15/2011
,它會將月份更改爲3(12+3)
。
應該在14
是「無效月」
package lesson4;
import java.util.*;
import java.text.*;
public class ConvertDate {
static String Month;
static String fulldate;
static int month;
static int[] montharray={1,2,3,4,5,6,7,8,9,10,11,12};
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter Date: ");
String ind = sc.nextLine();
//Date now = new Date();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat f = new SimpleDateFormat("dd");
SimpleDateFormat m = new SimpleDateFormat("MM");
Date d = null;
Date e=null;
Date g=null;
try {
d=df.parse(ind);
e=df.parse(ind);
g=df.parse(ind);
DateFormat df3 = DateFormat.getDateInstance(DateFormat.LONG);
fulldate = df3.format(d);
Month=m.format(g);
month =Integer.parseInt(Month);
String date =f.format(e);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("The entered date is: " + fulldate);
System.out.println("The entered month is: " + Month);
}
}
兄弟你能舉個例子..我會很棒 –
@Nizil。不,它不會。 DateFormat是執行此操作的正確方法。 –
@RohitJain我同意,'DateFormat'比字符串解析好得多,但忘了'setLenien(bool)',在發佈你的答案之前沒有看到另一個解決方案;) – NiziL