DateFormat parse(string , ParsePosition) Method in Java with Examples
Last Updated :
24 Jan, 2022
DateFormat class of java.text package is an abstract class that is used to format and parse dates for any locale. It allows us to format date to text and parse text to date. DateFormat class provides many functionalities to obtain, format, parse default date/time.
Note: DateFormat class extends Format class that means it is a subclass of Format class. Since DateFormat class is an abstract class, therefore, it can be used for date/time formatting subclasses, which format and parses dates or times in a language-independent manner.
Package-view:
java.text Package
DateFormat Class
parse(string , ParsePosition) Method
The parse(String the_text, ParsePosition position) method of DateFormat class is used to parse the text from a string to produce the Date. The method parses the text starting at the index given by a start position.
Syntax:
public abstract Date parse(String the_text, ParsePosition position)
Parameters: It takes 2 parameters:
- the_text: This is of the String type and refers to the string which is to be parsed to produce the date.
- position: This is of ParsePosition object type and refers to the information of the starting index of the parse.
Return Type: Returns the Date parsed from the string or Null in case of an error.
Example 1:
Java
import java.text.*;
import java.util.Calendar;
public class GFG {
public static void main(String[] args)
{
DateFormat DFormat
= new SimpleDateFormat( "MM/ dd/ yy" );
try {
Calendar cal = Calendar.getInstance();
String dt = "10/ 27/ 16" ;
System.out.println( "The unparsed"
+ " string is: " + dt);
cal.setTime(DFormat.parse(dt));
System.out.println( "Time parsed: "
+ cal.getTime());
}
catch (ParseException except) {
except.printStackTrace();
}
}
}
|
Output:
The unparsed string is: 10/ 27/ 16
Time parsed: Thu Oct 27 00:00:00 UTC 2016
Example 2:
Java
import java.text.*;
import java.util.Calendar;
public class GFG {
public static void main(String[] args)
{
DateFormat DFormat
= new SimpleDateFormat( "MM/ dd/ yy" );
try {
Calendar cal = Calendar.getInstance();
String dt = "01/ 29/ 19" ;
System.out.println( "The unparsed"
+ " string is: " + dt);
cal.setTime(DFormat.parse(dt));
System.out.println( "Time parsed: "
+ cal.getTime());
}
catch (ParseException except) {
except.printStackTrace();
}
}
}
|
Output
The unparsed string is: 01/ 29/ 19
Time parsed: Tue Jan 29 00:00:00 UTC 2019
Share your thoughts in the comments
Please Login to comment...