Java中的 SimpleDateFormat parse() 方法及示例
SimpleDateFormat 类的parse()方法用于从字符串中解析文本以生成日期。该方法从起始位置给定的索引开始解析文本。
句法:
public Date parse(String the_text, ParsePosition position)
参数:该方法有两个参数:
- the_text :这是String类型,指的是要解析以生成日期的字符串。
- position :这是ParsePosition对象类型,是指解析的起始索引的信息。
返回值:该方法要么返回从字符串解析的日期,要么返回 Null,以防出错。
下面的程序说明了 SimpleDateFormat 的 parse() 方法的工作:
示例 1:
Java
// Java Code to illustrate parse() method
import java.text.*;
import java.util.Calendar;
public class SimpleDateFormat_Demo {
public static void main(String[] args)
throws InterruptedException
{
SimpleDateFormat SDFormat
= new SimpleDateFormat("MM/ dd/ yy");
try {
Calendar cal = Calendar.getInstance();
// Use of .parse() method to parse
// Date From String
String dt = "10/ 27/ 16";
System.out.println("The unparsed"
+ " string is: " + dt);
cal.setTime(SDFormat.parse(dt));
System.out.println("Time parsed: "
+ cal.getTime());
}
catch (ParseException except) {
except.printStackTrace();
}
}
}
Java
// Java Code to illustrate parse() method
import java.text.*;
import java.util.Calendar;
public class SimpleDateFormat_Demo {
public static void main(String[] args)
throws InterruptedException
{
SimpleDateFormat SDFormat
= new SimpleDateFormat("MM/ dd/ yy");
try {
Calendar cal = Calendar.getInstance();
// Use of .parse() method to parse
// Date From String
String dt = "01/ 29/ 19";
System.out.println("The unparsed"
+ " string is: " + dt);
cal.setTime(SDFormat.parse(dt));
System.out.println("Time parsed: "
+ cal.getTime());
}
catch (ParseException except) {
except.printStackTrace();
}
}
}
输出:
The unparsed string is: 10/ 27/ 16
Time parsed: Thu Oct 27 00:00:00 UTC 2016
示例 2:
Java
// Java Code to illustrate parse() method
import java.text.*;
import java.util.Calendar;
public class SimpleDateFormat_Demo {
public static void main(String[] args)
throws InterruptedException
{
SimpleDateFormat SDFormat
= new SimpleDateFormat("MM/ dd/ yy");
try {
Calendar cal = Calendar.getInstance();
// Use of .parse() method to parse
// Date From String
String dt = "01/ 29/ 19";
System.out.println("The unparsed"
+ " string is: " + dt);
cal.setTime(SDFormat.parse(dt));
System.out.println("Time parsed: "
+ cal.getTime());
}
catch (ParseException except) {
except.printStackTrace();
}
}
}
输出:
The unparsed string is: 01/ 29/ 19
Time parsed: Tue Jan 29 00:00:00 UTC 2019