[英]How to convert “YYYY-MM-DD hh:mm:ss” to UNIX timestamp in Java?
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. 我以“ YYYY-MM-DD HH:MM:SS”的格式获取日期,并且需要以近似的增量计算从现在到现在的时间差:1分钟前,1小时前,等等。
Any pointers much appreciated :) 任何指针非常感激:)
Have a look at the SimpleDateFormat . 看看SimpleDateFormat 。
You can define your pattern and parse it into a Java Date Object: 您可以定义模式并将其解析为Java Date对象:
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. 第一行定义SimpleDateFormat(如果重复使用很多,也可以是静态的)。第二行解析您的输入。第三行将其转换为毫秒。
First you need to parse your date string to a Date
and then get the timestamp from that: 首先,您需要将日期字符串解析为Date
,然后从中获取时间戳:
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. 查看SimpleDateFormat
javadocs,以获取有关使用哪种格式字符串的信息。
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. 您需要将字符串转换成java.util.Date与SimpleDateFormat的协助(例如,参见- https://stackoverflow.com/search?q=simpledateformat+%5Bjava%5D ),然后获取自一月一日的毫秒数,1970年,00:00:00 GMT。
Date dt = new Date();
long unixTimeStamp = dt.getTime();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.