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);
}
}
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: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