Java code for getting current time

JavaTime

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

Both

new java.util.Date()

and

System.currentTimeMillis()

will give you current system time.

Solution 3 - Java

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.

Solution 4 - Java

System.currentTimeMillis()

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

Solution 5 - Java

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

Solution 6 - Java

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 !

Solution 7 - Java

Like said above you can use

Date d = new Date();

or use

Calendar.getInstance();

or if you want it in millis

System.currentTimeMillis()

Solution 8 - Java

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

Date d = new Date();

Solution 9 - Java

try this:

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

Solution 10 - Java

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

Solution 11 - Java

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.

Solution 12 - Java

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

Solution 13 - Java

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.

Solution 14 - Java

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsushmitaView Question on Stackoverflow
Solution 1 - JavaArturView Answer on Stackoverflow
Solution 2 - JavasleskeView Answer on Stackoverflow
Solution 3 - JavaBasil BourqueView Answer on Stackoverflow
Solution 4 - JavamP.View Answer on Stackoverflow
Solution 5 - JavaVerdigrassView Answer on Stackoverflow
Solution 6 - JavaDamiiiView Answer on Stackoverflow
Solution 7 - JavaNuno FurtadoView Answer on Stackoverflow
Solution 8 - JavaRaibazView Answer on Stackoverflow
Solution 9 - JavaThiagoView Answer on Stackoverflow
Solution 10 - JavaRomanView Answer on Stackoverflow
Solution 11 - Javamini-meView Answer on Stackoverflow
Solution 12 - JavaAlexView Answer on Stackoverflow
Solution 13 - JavaAdiView Answer on Stackoverflow
Solution 14 - JavaBrahim BoulkriatView Answer on Stackoverflow