java中如何将日期时间转换为时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9682891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to convert datetime to timestamp in java
提问by Yogendra Singh
forum member
论坛会员
I am having one problem with date time in java. Actually I am receiving the startdate in format 2012-02-27T01:10:10and I want to insert the received date to my database having datetime datatype.
我在 java 中遇到日期时间问题。实际上,我正在接收格式为 2012-02-27T01:10:10的开始日期,并且我想将接收到的日期插入到具有 datetime 数据类型的数据库中。
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
但是使用上面的代码,只有日期被添加到我的数据库中,例如 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.
我也想将时间添加到我的数据库中,但是当我将 SimpleDateFormat 更改为 SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 没有任何效果。
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.
请给我建议一些我可以应用的解决方案,这样我的时间也会被添加到数据库中。我使用 Hibernate JPA 作为我的持久层。
采纳答案by Kent
SimpleDateFormat's format() method doesn't return a Date type.
SimpleDateFormat 的 format() 方法不返回 Date 类型。
try this:
尝试这个:
Date startDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(sDate);
回答by Vaandu
Try this,
尝试这个,
yyyy-MM-dd'T'HH:mm:ss
回答by Vaandu
you can try like this....
你可以这样试试....
DateFormat format = new SimpleDateFormat("MMddyyHHmmss");
Date date = format.parse("022310141505");
回答by Sunil Kumar B M
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());
回答by vagelis
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.
当然只解析日期,因为您提供给 SimpleDateFormat 构造函数的模式只包含日期部分!将时间部分添加到它,它会解析时间也很好。