2013-08-02 97 views
0

在下面的代码 输入:爪哇日期转换

Enter Date: 3/2/2011 

输出:

Entered Date is February 3, 2011 
Entered Month is 02 

问题是,当我输入这个日期3/14/2012,日期格式功能自动更改一个月12+22月)。如果我输入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); 

} 
} 
+0

兄弟你能举个例子..我会很棒 –

+0

@Nizil。不,它不会。 DateFormat是执行此操作的正确方法。 –

+0

@RohitJain我同意,'DateFormat'比字符串解析好得多,但忘了'setLenien(bool)',在发布你的答案之前没有看到另一个解决方案;) – NiziL

回答

4

对于每个DateFormat实例,你需要调用setLenient虚假的说法:

DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); 
df.setLenient(false); 
DateFormat f = new SimpleDateFormat("dd"); 
f.setLenient(false); 
DateFormat m = new SimpleDateFormat("MM"); 
m.setLenient(false); 

DateFormat#setLenient(boolean)文档:

随着宽松的解析,解析器可以使用启发式来解释不精确的输入这个对象的格式。通过严格的解析,输入必须匹配这个对象的格式。

+0

伟大的Rohit ..但我可以想要从数组中检查月份..我限制使用数组,如果我在月中输入14,那么它应该显示无效的月份....你的代码只是捕捉异常 –

+0

@JamesBlent。您可以捕获异常,并显示您自己的消息。你可以搜索一些很好的异常处理教程。 –

+0

是的,我有缓存异常,“无效日期”..但我怎么能给出错误使用数组..我已经声明数组中的代码...请帮助 –

2

参考给出错误这些格式Java Date Format Docs:在第二位,而

Formats for datetime

DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); 

你期待月输入首先放置它。

尝试:

DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 
0

您是否尝试过在您的DateFormat上使用“setLenient(false)”来强制DateFormat严格分析输入? 我还没有尝试过,但最近偶然发现了这个功能。