當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。