-2

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

4

3 回答 3

17

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

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 SimpleDateFormat at URL

Cheers !!

于 2013-09-04T21:16:56.573 回答
2
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);

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

于 2013-09-04T21:16:10.863 回答
-1

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

String str = "2005-10-30 T 10:46 UTC";
String hours = str.substring(13, 15);
String minutes = str.substring(16, 18);
于 2013-09-04T21:15:57.773 回答