theJava
theJava

Reputation: 15034

Getting time from a Date Object

I have an date object from which i need to getTime(). The issue is it always shows 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

Upvotes: 10

Views: 56833

Answers (3)

dmvstar
dmvstar

Reputation: 41

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
 }

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1074038

You should pass the actual Date object into format, not a 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 implied by your question but not actually stated), that should work fine.

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.

That means your Date object has zeroes for hours, minutes, and seconds, like so:

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);
    }
}

Upvotes: 23

M Sach
M Sach

Reputation: 34424

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()));

Upvotes: 3

Related Questions