我想将String dateStr= "2013-12-02 14:02:25"
转换为日期。
解决方案很简单,但我没有获得正确的输出。
代码是:
try {
Date thedate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateStr); System.out.println(thedate);
} catch (ParseException e1) {
e1.printStackTrace();
}
输出结果为:Sun Dec 02 14:02:25 GMT+03:00 2013
更新
我想要的是获得与字符串相同的格式。
答案 0 :(得分:2)
您的代码正确格式化日期。它得到String
并将其解析为Date
。当您打印Date
时,java使用Date.toString()
方法。
如果要以特定格式打印,则需要使用其他格式(如果模式相同,则需要使用相同的格式)SimpleDateFormat
并调用format
方法。
答案 1 :(得分:1)
使用此:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(thedate));
答案 2 :(得分:1)
我刚试过这个:
String str = "2013-12-02 14:02:25";
try {
Date thedate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(str);
System.out.println(thedate);
Calendar cal = Calendar.getInstance();
cal.setTime(thedate);
System.out.println("-->"+cal.get(Calendar.DATE)+"::"+(cal.get(Calendar.MONTH)+1)+":"+cal.get(Calendar.YEAR));
} catch (java.text.ParseException ex) {
Logger.getLogger(Search.class.getName()).log(Level.SEVERE, null, ex);
}
输出是: - →2 :: 12:2013
这是你在找什么?
答案 3 :(得分:1)
如果你想以同样的格式出去,只需format
使用你的SimpleDateFormat
。
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date=df.parse("2013-12-02 14:02:25");
System.out.println(df.format(date));
答案 4 :(得分:1)
喜欢这个
SimpleDateFormat df = nnew SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = df.parse("2013-12-02 14:02:25");
String formattedDate = df.format(date);
System.out.println(formattedDate);
答案 5 :(得分:1)
试试这个简单的代码:
String date_time= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());