Saturday, October 25, 2025
HomeLanguagesJavaJava DateFormat parseObject() Method with Examples

Java DateFormat parseObject() Method with Examples

The parseObject() method of DateFormat class will return the data by parsing a string to a SimpleDateFormat object.

Syntax:

public Object parseObject(source,pos)

Parameters: This method accepts two parameters

  • source: It is a string which is needed to be parsed.
  • pos: It is the ParsePosition object with an index.

Return value: This method will return a date parsed from a string and null in case of an error.

Example 1:

Java




// Java program to illustrate 
// DateFormat parseObject() Method 
  
// importing the required packages
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
  
  
class Testclass {
    public static void main (String[] args) {
          
          Date d = new Date();
        
          // printing the actual date value
        System.out.println("Actual Date : "+d);        
            
          // initializing the SimpleDateFormat
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
            
          // passing a string to parseObject() 
          // method and converting it into date
        d = (Date) sdf.parseObject("10-11-2021");    
        
          // printing the parsed date value
        System.out.println("Parsed Date : "+d);                    
    }
}


Output

Actual Date : Tue Dec 14 09:49:39 UTC 2021
Parsed Date : Mon Oct 11 00:00:00 UTC 2021

Example 2:

Java




// Java program to illustrate 
// DateFormat parseObject() Method 
  
// importing the required packages
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
  
class Testclass {
    public static void main(String[] args)
    {
  
        // initializing the Date
        Date d = new Date();
  
        // printing the actual date value
        System.out.println("Actual Date : " + d);
  
        // initializing the SimpleDateFormat
        SimpleDateFormat sdf
            = new SimpleDateFormat("MM/dd/yy hh.mm.ss");
  
        // passing a string to parseObject()
        // method and converting it into date
        d = (Date)sdf.parseObject("04/10/21 19.30.45");
  
        // printing the parsed date value
        System.out.println("Parsed Date : " + d);
    }
}


Output

Actual Date : Tue Dec 14 09:53:31 UTC 2021
Parsed Date : Sat Apr 10 19:30:45 UTC 2021
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS