Java中如何将字符串转换到日期
时间:2020-02-23 14:34:16 来源:igfitidea点击:
在本教程中,我们将看到如何将字符串转换为Java中的Date对象。
当我们具有格式化的字符串时使用它,并且需要将其转换为Date Object.you也可以检查如何将日期转换为字符串
Java程序:
package org.igi.theitroad; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class StringToDateExample { public static void main(String[] args) { String strDate1 = "25/01/2015"; String strDate2 = "25-Jan-2014"; String strDate3 = "Mon, Jan 25 2015"; /* * We will use SimpleDateFormat's parse method to convert String to date. */ try{ SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy"); //use parse method of SimpleDateFormat to convert it to date //Date object will be returned by parse method Date date1 = sdf1.parse(strDate1); System.out.println("Date in format dd/MM/yyyy " + sdf1.format(date1)); SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy"); Date date2 = sdf2.parse(strDate2); System.out.println("Date in format dd-MMM-yyyy: " + sdf2.format(date2)); SimpleDateFormat sdf3 = new SimpleDateFormat("E, MMM dd yyyy"); Date date3 = sdf3.parse(strDate3); System.out.println("Date in format E, MMM dd yyyy: " + sdf3.format(date3)); }catch(ParseException e){ //This exception will be thrown if string can not be converted to date System.out.println("Java String could not be converted to Date: " + e); } } }
运行上面的程序时,我们将获取以下输出:
Date in format dd/MM/yyyy 25/01/2015 Date in format dd-MMM-yyyy: 25-Jan-2014 Date in format E, MMM dd yyyy: Mon, Jan 25 2015