Java 从时间戳中获取小时数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18623838/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:36:25  来源:igfitidea点击:

Java get hours from a timestamp

java

提问by Kidambi Manoj

I'm reading the timestamp from a file, and convert it using SimpleDataFormat to the timestamp format received from SQL, for some reason, I have to compare the minutes and seconds of both the stamps. Is there an optimized to extract the hours (without parsing it) from the stamp I have converted using SimpleDateFormat

我正在从文件中读取时间戳,并使用 SimpleDataFormat 将其转换为从 SQL 接收的时间戳格式,出于某种原因,我必须比较两个时间戳的分钟和秒。是否有优化以从我使用 SimpleDateFormat 转换的邮票中提取小时数(不解析它)

采纳答案by Sachin Thapa

You need to use SimpleDateFormatwhich can parse a give date to format you require.

您需要使用SimpleDateFormatwhich 可以解析给定日期以格式化您需要的格式。

Timestamp stamp = new Timestamp(System.currentTimeMillis());
Date date = new Date(stamp.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy h:mm:ss a");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String formattedDate = sdf.format(date);

Read more about SimpleDateFormatat URL

SimpleDateFormatURL 上阅读更多信息

Cheers !!

干杯!!

回答by Paul Vargas

The quick and easy way, if you have a string with the date in some fixed format:

快速简便的方法,如果您有一个带有某种固定格式的日期的字符串:

String str = "2005-10-30 T 10:46 UTC";
String hours = str.substring(13, 15);
String minutes = str.substring(16, 18);

回答by MK.

SimpleDateFormat sdf=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
Date date = null;
try {
    date = sdf.parse("Wed Sep 4 13:41:12 UTC 2013");
} catch (ParseException ex) {
    // ...
    System.exit(-1);
}
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
cal.setTime(date);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);

(of course you will have to change date format to match your string, I just put in a random one from the internets)

(当然,您必须更改日期格式以匹配您的字符串,我只是从互联网上随机放入一个)