浅析Java中Data类的实际应用
将文本数据解析成日期对象
假设我们有一个文本字符串包含了一个格式化了的日期对象, 而我们希望解析这个字符串并从文本日期数据创建一个日期对象. 我们将再次以格式化字符串"MM-dd-yyyy" 调用SimpleDateFormat类, 但是这一次, 我们使用格式化解析而不是生成一个文本日期数据. 我们的例子, 显示在下面, 将解析文本字符串"9-29-2001"并创建一个值为001736000000 的日期对象.
例子程序:
import java.text.SimpleDateFormat; import java.util.Date; public class DateExample3 { public static void main(String[]args) { //自己替换[] // Create a date formatter that can parse dates of // the form MM-dd-yyyy. SimpleDateFormat bartDateFormat = new SimpleDateFormat("MM-dd-yyyy"); // Create a string containing a text date to be parsed. String dateStringToParse = "9-29-2001"; try { // Parse the text version of the date. // We have to perform the parse method in a // try-catch construct in case dateStringToParse // does not contain a date in the format we are expecting. Date date = bartDateFormat.parse(dateStringToParse); // Now send the parsed date as a long value // to the system output. System.out.println(date.getTime()); } catch (Exception ex) { System.out.println(ex.getMessage()); } } }
0
相关文章