-1

Wha would be the equivalent in Java for this C# code:

DateTime.Now.TimeOfDay //This
DateTime.Now.ToString("h:mm:ss tt") //Or This  

I'm finding a lot of things, some of them may be deprecated because it has 2 years or more, others are really complex for such a simple thing, and I'm sure there is a simpler way to do so.

I tried:

import java.util.Date;

Date d = new Date();
System.out.println(d);   //Result:  Wed Oct 28 00:46:29 2015  

If I try:  

System.out.println(d.getTime()); //Result:  1446000426285

I need to get only time: H:mm:ss

PlayHardGoPro
  • 2,791
  • 10
  • 51
  • 90
  • `Calendar.getInstance().getTime().toString()` will get you `dow mon dd hh:mm:ss zzz yyy` which you can then just parse? – 3kings Oct 28 '15 at 02:52

2 Answers2

3

You can use SimpleDateFormat in java. date.getTime() gives you the milliseconds since January 1, 1970, 00:00:00 GMT.

    Date date = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss");
    System.out.println(dateFormat.format(date));
Bon
  • 3,073
  • 5
  • 21
  • 40
2

Generally speaking, in Java, date/time objects are just a container for the amount of time which has passed since a given point in time (like the Unix epoch), so they tend not to have there own concept of formatting.

Formatting is normally managed by a supporting API, like java.text.DateFormat or java.time.format.DateTimeFormatter

If you're using Java 8, you could start with LocalTime

LocalTime time = LocalTime.now();
System.out.println(DateTimeFormatter.ISO_LOCAL_TIME.format(time));

which prints 13:51:13.466.

If you need a specific format, you can supply your own pattern to DateTimeFormatter, something like System.out.println(DateTimeFormatter.ofPattern("h:mm:ss a").format(time)); which prints 1:52:31 PM

Have a look at Date and Time Classes for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366