如何将“YYYY-MM-DD hh:mm:ss”转换为Java中的UNIX时间戳? [英] How to convert “YYYY-MM-DD hh:mm:ss” to UNIX timestamp in Java?
问题描述
或者,也许您知道如何解决此问题的更好方法。我以YYYY-MM-DD HH:MM:SS的格式获取日期,需要计算现在之间的时间差,然后以近似的增量:1分钟前,1小时前等等。
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 :)
推荐答案
看一下 SimpleDateFormat 。您可以定义模式并将其解析为Java Date Object:
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 = formate.parse("your string goes here");
long timestamp = date.getTime();
第一行定义了SimpleDateFormat(如果你重复使用它也可以是静态的)
第二行解析您的输入
第三行将其转换为毫秒。
First line defines the SimpleDateFormat (can also be static if you reuse it a lot) Second line parses your input Third line converts it into milliseconds.
这篇关于如何将“YYYY-MM-DD hh:mm:ss”转换为Java中的UNIX时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!