Getting time from a Date object

I have a date object from which I need getTime() . The problem is that 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 always the time '00:00:00' . Should I add Time to my Date Object

+4
source share
3 answers

You should pass the actual Date object to format , not long :

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

Assuming any Utils.getDateObject(DateObject) actually returns Date (which is implied by your question but not really indicated), this should work fine.

For example, this works great:

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

Repeat your comment below:

Thanks TJ, but actually I still get 00:00:00 as time.

This means that your Date object has zeros for hours, minutes and seconds, for example:

 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); } } 
+12
source

Besides the above solution, you can also use a calendar class if you do not have a 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())); 
+2
source

For example, you can use the following 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 } 
+2
source

Source: https://habr.com/ru/post/1481217/


All Articles