2013-02-13 12 views
12

जब मैं निम्नलिखित कोड चलाता हूं तो मुझे एक स्टैकट्रैक की उम्मीद होगी, लेकिन इसके बजाय ऐसा लगता है कि यह मेरे मान के दोषपूर्ण हिस्से को अनदेखा करता है, ऐसा क्यों होता है?अक्षरों के साथ non-lenient SimpleDateFormat पार्स तिथियां क्यों होती हैं?

package test; 

import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 

public class Test { 
    public static void main(final String[] args) { 
    final String format = "dd-MM-yyyy"; 
    final String value = "07-02-201f"; 
    Date date = null; 
    final SimpleDateFormat df = new SimpleDateFormat(format); 
    try { 
     df.setLenient(false); 
     date = df.parse(value.toString()); 
    } catch (final ParseException e) { 
     e.printStackTrace(); 
    } 
    System.out.println(df.format(date)); 
    } 

} 

उत्पादन होता है:

07-02-0201

उत्तर

10

DateFormat.parse दस्तावेज़ों (जो SimpleDateFormat द्वारा विरासत में मिली है) का कहना है:

The method may not use the entire text of the given string. 
final String value = "07-02-201f"; 

आपके मामले में (201 एफ) यह 201 तक वैध स्ट्रिंग को पार्स करने में सक्षम था, यही कारण है कि इससे आपको कोई त्रुटि नहीं मिल रही है।

"फेंकता" एक ही विधि की धारा नीचे के रूप में परिभाषित किया गया है:

ParseException - if the beginning of the specified string cannot be parsed 

तो अगर आप

final String value = "07-02-f201"; 

करने के लिए अपने स्ट्रिंग को बदलने की कोशिश आप पार्स अपवाद मिल जाएगा , क्योंकि निर्दिष्ट स्ट्रिंग की शुरुआत को पार्स नहीं किया जा सकता है।

1

पुष्टि की गई ... मैंने यह भी पाया कि "07-02-2013," 07-02-2012 तारीख "संकलित है। हालांकि, "bar07-02-2011" नहीं है।

SimpleDateFormat में कोड से, ऐसा लगता है कि पार्सिंग उस क्षण को समाप्त कर देती है जब एक अवैध चरित्र मिल जाता है जो मिलान को तोड़ देता है। हालांकि, यदि उस स्ट्रिंग को पहले से ही उस बिंदु पर पार्स किया गया है, तो यह मान्य है।

4

आप देख सकते हैं कि संपूर्ण स्ट्रिंग को निम्नानुसार पार्स किया गया था या नहीं।

ParsePosition position = new ParsePosition(0); 
    date = df.parse(value, position); 
    if (position.getIndex() != value.length()) { 
     throw new ParseException("Remainder not parsed: " 
       + value.substring(position.getIndex())); 
    } 

इसके अलावा जब एक अपवाद parse से फेंक दिया गया था position भी getErrorIndex() निकलेगा।

संबंधित मुद्दे