如何在Java中将String转换为日期格式?

时间:2014-04-22 11:23:05

标签: java

我正在研究Java。我有String,我想将其转换为Date格式。有关更多详细信息,请参阅代码行。

String dateString = "4:16:06 PM";

我想将其转换为下面的Date

 Date convertedDate  = 2014-04-22 16:16:06.00

我该怎么做?

4 个答案:

答案 0 :(得分:2)

试试这个:

// get current date
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
String a = dateFormat1.format(new Date());

// add current date to your time string
String dateString = a + " 4:16:06 PM";

SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd h:mm:ss a");
try {
    // parse it. This is you date object.
    Date d = dateFormat2.parse(dateString);
} catch (ParseException ex) {
    ex.printStackTrace();
}

答案 1 :(得分:1)

我认为您正在寻找以下内容:

    DateFormat df1 = new SimpleDateFormat("h:mm:ss a");
    DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS");

    String dateString = "4:16:06 PM";

    Date date;
    try {
        Calendar cal = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        date = df1.parse(dateString);
        cal.setTime(date);

        // Reset year, month, day to current state
        cal.set(Calendar.YEAR, cal2.get(Calendar.YEAR));
        cal.set(Calendar.MONTH, cal2.get(Calendar.MONTH));
        cal.set(Calendar.DAY_OF_MONTH, cal2.get(Calendar.DAY_OF_MONTH));

        Date convertedDate = cal.getTime();
        System.out.println(df2.format(convertedDate));

    } catch (ParseException e) {
        e.printStackTrace();
    }

答案 2 :(得分:0)

试试这个,

String str_date="13-09-2011";
DateFormat formatter ; 
Date date ; 
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date); 
System.out.println("Date " +date.getTime());

答案 3 :(得分:0)

试试这个

 public class DateClass
 {
public static void main(String[] args) throws Exception {
String target = "4:16:06 PM";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
DateFormat dff = new SimpleDateFormat("HH:mm:ss");
Date d=new Date();
String abc="4:16:06 PM";
Date result =  new SimpleDateFormat("h:mm:ss a").parse(abc);  

  System.out.println("The result is "+df.format(d)+" "+dff.format(result));
 }
   }

如果你不理解它,请随意提出任何问题,并确认它是否有效?