how to convert datetime to timestamp in java

半城伤御伤魂 提交于 2020-01-11 10:45:22

问题


forum member

I am having one problem with date time in java. Actually I am receiving the startdate in format 2012-02-27T01:10:10 and I want to insert the received date to my database having datetime datatype.

Actually I tried to convert the startdate received to datetime by below code

String sDate = jsonObject.get("StartDate").toString();
String eDate = jsonObject.get("EndDate").toString();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
Date startD = sdf.format(sDate);
Date endD = sdf.format(eDate);

but with the above code only date gets added to my database like 2012-02-27 00:00:00

I want to add the time also to my database but when I change the SimpleDateFormat to SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); nothing works.

please suggest me some solution I can apply so my time also gets added to database. I am using Hibernate JPA as my persistence layer.


回答1:


SimpleDateFormat's format() method doesn't return a Date type.

try this:

Date startDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(sDate);



回答2:


Try this,

yyyy-MM-dd'T'HH:mm:ss



回答3:


String sDate = jsonObject.get("StartDate").toString();
String eDate = jsonObject.get("EndDate").toString();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
Date startD = sdf.format(sDate);
Timestamp startTime = new Timestamp(startD.getTime());

Date endD = sdf.format(eDate);
Timestamp endTime = new Timestamp(endD.getTime());



回答4:


Of course only the date is parsed, since the pattern you provided to the SimpleDateFormat constructor only contains the date part! Add the time part to it and it will parse the time too just fine.




回答5:


you can try like this....

DateFormat format = new SimpleDateFormat("MMddyyHHmmss");
Date date = format.parse("022310141505");


来源:https://stackoverflow.com/questions/9682891/how-to-convert-datetime-to-timestamp-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!