How to convert “YYYY-MM-DD hh:mm:ss” to UNIX timestamp in Java?

六月ゝ 毕业季﹏ 提交于 2019-12-18 07:24:41

问题


Or, maybe you know a better approach how to solve this problem. I get dates in the format of "YYYY—MM-DD HH:MM:SS" and need to calculate time difference between now then in approximate increments: 1 minute ago, 1 hour ago, etc.

Any pointers much appreciated :)


回答1:


Have a look at the SimpleDateFormat.

You can define your pattern and parse it into a Java Date Object:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse("your string goes here");
long timestamp = date.getTime();

The first line defines the SimpleDateFormat (can also be static if you reuse it a lot) The second line parses your input The third line converts it into milliseconds.




回答2:


First you need to parse your date string to a Date and then get the timestamp from that:

final SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");

final String myDateString = "someDateString";
final Date date = dateFormat.parse(myDateString);

final long timestamp = date.getTime();

Have a look at the SimpleDateFormat javadocs for information on which format string to use.




回答3:


You need to convert your string into java.util.Date with the assistance of SimpleDateFormat (for examples see - https://stackoverflow.com/search?q=simpledateformat+%5Bjava%5D) and then get the number of milliseconds since January 1, 1970, 00:00:00 GMT.

Date dt = new Date();
long unixTimeStamp = dt.getTime();


来源:https://stackoverflow.com/questions/15322780/how-to-convert-yyyy-mm-dd-hhmmss-to-unix-timestamp-in-java

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