当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Java DateFormat parseObject()用法及代码示例

DateFormat 类的 parseObject() 方法将通过将字符串解析为 SimpleDateFormat 对象来返回数据。

用法:

public Object parseObject(source,pos)

参数:该方法接受两个参数

  • source:它是一个需要解析的字符串。
  • pos:它是带有索引的 ParsePosition 对象。

返回值:此方法将返回从字符串解析的日期,如果出现错误,则返回 null。



范例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);                    
    }
}
输出
Actual Date:Tue Dec 14 09:49:39 UTC 2021
Parsed Date:Mon Oct 11 00:00:00 UTC 2021

范例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);
    }
}
输出
Actual Date:Tue Dec 14 09:53:31 UTC 2021
Parsed Date:Sat Apr 10 19:30:45 UTC 2021



相关用法


注:本文由纯净天空筛选整理自akashdeepkatari大神的英文原创作品 Java DateFormat parseObject() Method with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。