Java 从日期对象中获取时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16592493/
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
Getting time from a Date Object
提问by theJava
I have an date object from which i need to getTime()
. The issue is it always shows 00:00:00
.
我有一个我需要的日期对象getTime()
。问题是它总是显示00:00:00
.
SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm:ss");
long date = Utils.getDateObject(DateObject).getTime();
String time = localDateFormat.format(date);
Why is the time always '00:00:00'
. Should i append Time to my Date Object
为什么时间总是'00:00:00'
。我应该追加Time to my Date Object
采纳答案by T.J. Crowder
You should pass the actual Date
object into format
, not a long
:
您应该将实际Date
对象传递给format
,而不是传递给long
:
SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm:ss");
String time = localDateFormat.format(Utils.getDateObject(DateObject));
Assuming that whatever Utils.getDateObject(DateObject)
is actually returns a Date
(which is impliedby your question but not actually stated), that should work fine.
假设Utils.getDateObject(DateObject)
实际上返回的是 a Date
(这是您的问题所暗示的,但实际上并未说明),那应该可以正常工作。
For example, this works perfectly:
例如,这完美地工作:
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);
}
}
Re your comment below:
在下面回复您的评论:
Thanks TJ, but actually i am still getting 00:00:00 as time.
谢谢 TJ,但实际上我仍然在 00:00:00 作为时间。
That means your Date
object has zeroes for hours, minutes, and seconds, like so:
这意味着您的Date
对象的小时、分钟和秒都为零,如下所示:
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(2013, 4, 17)); // <== Only changed line (and using a deprecated API)
System.out.println(time);
}
}
回答by M Sach
Apart from above solution , you can also use calendar class if you don't have specific requirement
除了上述解决方案,如果您没有特定要求,您还可以使用日历类
Calendar cal1 =new GregorianCalendar() or Calendar.getInstance();
SimpleDateFormat date_format = new SimpleDateFormat("HH:mm:ss");
System.out.println(date_format.format(cal1.getTime()));
回答by dmvstar
For example, you can use next code:
例如,您可以使用下一个代码:
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
}