字符串日期Java [英] String Date Java
问题描述
我有一个String对象,表示这种格式的日期/时间:2013-06-09 14:20: 00(yyyy-MM-dd HH:mm:ss)
我想把它转换成一个Date对象,所以我可以对它进行计算,
我尝试过:
String string = 2013-06-09 14:20:00
Date date = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss)。parse(string);
System.out.println(date);
//打印星期一12月31日00:00:00 GMT 2012
任何帮助赞赏
好的,所以我现在更新了我的代码如下,当我打印日期时,我得到正确的日期/时间,但这是正确的实现:
DateFormat dateFormat = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss);
String string =2013-06-09 14:20:00;
Date date = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss)。parse(string);
System.out.println(dateFormat.format(date));
//印刷2013-06-09 14:20:00
Thx给所有人回答/评论到目前为止
格式错误。使用此代替:
yyyy-dd-MM HH:mm:ss
确实,你的最后一个程序版本是可以的,除了你不需要两次声明 SimpleDateFormat
。简单地:
DateFormat dateFormat = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss);
String string =2013-06-09 14:20:00;
Date date = dateFormat.parse(string);
System.out.println(dateFormat.format(date));
// Im new to java programming
I have a String object that represents a date/time in this format : "2013-06-09 14:20:00" (yyyy-MM-dd HH:mm:ss)
I want to convert it to a Date object so i can perform calculations on it but im confused on how to do this.
I tried :
String string = "2013-06-09 14:20:00";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(string);
System.out.println(date);
//Prints Mon Dec 31 00:00:00 GMT 2012
Any help appreciated
Ok so I have now updated my code to as follows i'm getting the correct date/time now when I print the date but is this the correct implementation :
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String string = "2013-06-09 14:20:00";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(string);
System.out.println(dateFormat.format(date));
//prints 2013-06-09 14:20:00
Thx to everyone that's answered/commented thus far
The format is wrong. Use this instead:
"yyyy-dd-MM HH:mm:ss"
Indeed your last program version is ok, except you don't need to declare the SimpleDateFormat
twice. Simply:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String string = "2013-06-09 14:20:00";
Date date = dateFormat.parse(string);
System.out.println(dateFormat.format(date));
这篇关于字符串日期Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!