[java] Java code for getting current time

I am searching code in java for fetching or synchronizing my local PC system time into my application.

This question is related to java time

The answer is


new Date().getTime() is bugged.

    Date date = new Date();
    System.out.println(date);
    System.out.println(date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds());
    long t1 = date.getTime();
    System.out.println((t1 / 1000 / 60 / 60) % 24 + ":" + (t1 / 1000 / 60) % 60 + ":" + (t1 / 1000) % 60);
    long t2 = System.currentTimeMillis();
    System.out.println((t2 / 1000 / 60 / 60) % 24 + ":" + (t2 / 1000 / 60) % 60 + ":" + (t2 / 1000) % 60);

It returns me the wrong time millis. System.currentTimeMillis() too. Since I ask the Date instance to tell me the corresponding time millis it must return the matching ones not others from a different time zone. Funny how deprecated methods are the only ones which return correct values.


Like said above you can use

Date d = new Date();

or use

Calendar.getInstance();

or if you want it in millis

System.currentTimeMillis()

To get system time use Calendar.getInstance().getTime()

And you should get the new instance of Calendar each time to have current time.

To change system time from java code you can use a command line


tl;dr

Instant.now()  // UTC

…or…

ZonedDateTime.now(
    // Specify time zone.
    ZoneId.of( "Pacific/Auckland" )
)  

Details

The bundled java.util.Date/.Calendar classes are notoriously troublesome. Avoid them. They are now legacy, supplanted by the java.time framework.

Instead, use either:

java.time

ZonedDateTime zdt = ZonedDateTime.now();

If needed for old code, convert to java.util.Date. Go through at Instant which is a moment on the timeline in UTC.

java.util.Date date = java.util.Date.from( zdt.toInstant() );

Time Zone

Better to specify explicitly your desired/expected time zone rather than rely implicitly on the JVM’s current default time zone.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( zoneId );  // Pass desired/expected time zone.

Table of date-time types in Java, both modern and legacy

Joda-Time

FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.

DateTime now = DateTime.now();

To convert from a Joda-Time DateTime object to a java.util.Date for inter-operating with other classes…

java.util.Date date = now.toDate();

Search StackOverflow before posting. Your question has already been asked and answered.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


I understand this is quite an old question. But would like to clarify that:

Date d = new Date() 

is depriciated in the current versions of Java. The recommended way is using a calendar object. For eg:

Calendar cal = Calendar.getInstance();
Date currentTime = cal.getTime();

I hope this will help people who may refer this question in future. Thank you all.


You can use new Date () and it'll give you current time.

If you need to represent it in some format (and usually you need to do it) then use formatters.

DateFormat df = DateFormat.getDateTimeInstance (DateFormat.MEDIUM, DateFormat.MEDIUM, new Locale ("en", "EN"));
String formattedDate = df.format (new Date ());

Try this:

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class currentTime {

    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        System.out.println( sdf.format(cal.getTime()) );
    }

}

You can format SimpleDateFormat in the way you like. For any additional information you can look in java api:

SimpleDateFormat

Calendar


System.currentTimeMillis()

everything else works off that.. eg new Date() calls System.currentTimeMillis().


Just to inform for furthers developers, and thankfully to Basil Bourque, I just wanna add my stone to this topic.

If you want simply get the HH:MM:SS format then do this:

LocalTime hour = ZonedDateTime.now().toLocalTime().truncatedTo(ChronoUnit.SECONDS);

Cheers.

P.S.: This will work only at least with Java 8 !


try this:

final String currentTime    = String.valueOf(System.currentTimeMillis());

try this to get the current date.You can also get current hour, minutes and seconds by using getters :

new Date(System.currentTimeMillis()).get....()

Try this way, more efficient and compatible:

SimpleDateFormat time_formatter = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss.SSS");
String current_time_str = time_formatter.format(System.currentTimeMillis());
//Log.i("test", "current_time_str:" + current_time_str);

Not really sure about what you meant, but you probably just need

Date d = new Date();

Both

new java.util.Date()

and

System.currentTimeMillis()

will give you current system time.