从日期对象中获取时间

时间:2013-05-16 16:11:09

标签: java date time

我有一个日期对象,我需要getTime()。问题是它始终显示00:00:00

SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm:ss");
long date = Utils.getDateObject(DateObject).getTime();
String time = localDateFormat.format(date);

为什么时间总是'00:00:00'。我应该追加Time to my Date Object

3 个答案:

答案 0 :(得分:19)

您应该将实际的Date对象传递给format,而不是long

SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm:ss");
String time = localDateFormat.format(Utils.getDateObject(DateObject));

假设Utils.getDateObject(DateObject)实际上只返回{​​{1}}(你的问题暗示但未实际说明),那应该可以正常工作。

例如,这非常有效:

Date

重新评论以下内容:

  

谢谢TJ,但实际上我的时间仍然是00:00:00。

这意味着您的import java.util.Date; import java.text.SimpleDateFormat; public class SDF { public static final void main(String[] args) { SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm:ss"); String time = localDateFormat.format(new Date()); System.out.println(time); } } 对象的小时,分​​钟和秒数为零,如下所示:

Date

答案 1 :(得分:3)

例如,您可以使用下一个代码:

 public static int getNotesIndexByTime(Date aDate){
    int ret = 0;
    SimpleDateFormat localDateFormat = new SimpleDateFormat("HH");
    String sTime = localDateFormat.format(aDate);
    int iTime = Integer.parseInt(sTime);
    return iTime;// count of hours 0-23
 }

答案 2 :(得分:2)

除上述解决方案外,如果您没有特定要求,也可以使用日历类

Calendar cal1 =new GregorianCalendar() or Calendar.getInstance();
SimpleDateFormat date_format = new SimpleDateFormat("HH:mm:ss");
System.out.println(date_format.format(cal1.getTime()));