157

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

eckes
  • 10,103
  • 1
  • 59
  • 71

14 Answers14

167

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

osvein
  • 625
  • 2
  • 10
  • 31
Artur
  • 3,284
  • 2
  • 29
  • 35
  • 7
    no need to call the cal.getTime() method 2 time, it could have been assigned to string after formatting the date like this .......SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");String loginTime = sdf.format(cal.getTime()); – Bamara Coulibaly May 22 '14 at 19:23
  • 2
    FYI, the troublesome classes used here are now legacy, supplanted by the *java.time* classes. – Basil Bourque Mar 07 '18 at 02:58
  • 1
    For the lazy (oneliner, no imports, just copy-paste it): `new java.text.SimpleDateFormat("HH:mm:ss").format(java.util.Calendar.getInstance().getTime())` – Luc Mar 21 '19 at 08:59
151

Both

new java.util.Date()

and

System.currentTimeMillis()

will give you current system time.

Seki
  • 11,135
  • 7
  • 46
  • 70
sleske
  • 81,358
  • 34
  • 189
  • 227
51

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • 1
    Was his question also answered many times before 7 May '09? – skiwi Mar 23 '14 at 18:28
  • 1
    @skiwi (a) Actually, yes. [Here](http://stackoverflow.com/questions/308683/how-can-i-get-the-current-date-and-time-in-utc-or-gmt-in-java). [Here](http://stackoverflow.com/q/74620/642706). (b) However, I did fail to notice the age of the question. – Basil Bourque Mar 23 '14 at 18:52
10

System.currentTimeMillis()

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

mP.
  • 18,002
  • 10
  • 71
  • 105
9

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);
Verdigrass
  • 1,203
  • 12
  • 14
8

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 !

Damiii
  • 1,363
  • 4
  • 25
  • 46
5

Like said above you can use

Date d = new Date();

or use

Calendar.getInstance();

or if you want it in millis

System.currentTimeMillis()
Nuno Furtado
  • 4,548
  • 8
  • 37
  • 57
4

try this:

final String currentTime    = String.valueOf(System.currentTimeMillis());
Thiago
  • 12,778
  • 14
  • 93
  • 110
4

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

Date d = new Date();
Raibaz
  • 9,280
  • 10
  • 44
  • 65
3

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.

mini-me
  • 221
  • 2
  • 3
  • I am very, very sceptical of your claims of bugs. Unless your system clock has been set incorrectly, of course. – Ole V.V. Apr 07 '18 at 12:59
3

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 ());
Roman
  • 64,384
  • 92
  • 238
  • 332
2

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

Alex
  • 2,438
  • 23
  • 30
1

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.

Adi
  • 361
  • 1
  • 5
  • 23
  • 2
    The top-voted answer already has the Calendar version. What exactly does your post add? – Mat Mar 23 '14 at 14:37
  • Yes. But all other answwers speak about the depriciated constructor. Just added a clarification. Thank you. – Adi Mar 23 '14 at 14:40
  • Incorrect: The [`Date()`](http://download.java.net/jdk8/docs/api/java/util/Date.html#Date--) constructor is *not* deprecated (as of Java 8). Other methods on that class are deprecated, but not that one. Practically speaking, you should consider it deprecated and instead be using either [Joda-Time](http://www.joda.org/joda-time/) or the new [java.time package](http://download.java.net/jdk8/docs/api/index.html?java/time/package-summary.html) in Java 8. – Basil Bourque Mar 23 '14 at 18:13
1

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

new Date(System.currentTimeMillis()).get....()
Brahim Boulkriat
  • 984
  • 2
  • 9
  • 21