Question of System.currentTimeMillis();

Hi there,
I got some problem in method "System.currentTimeMillis()" .
The part of my function is:
     long c= System.currentTimeMillis();
     System.out.println("before time="+c);
          some codes here
try{new Thread().sleep(1000);}catch(Exception e){} //sleep for additional 1 second
     long b= System.currentTimeMillis();
     System.out.println("after time="+b);
     c=c-b;
     System.out.println("run time="+c);
the output is:
     before time=1001526336640
     after time= 1001526345985
     run time= -9345
Couple things I could understand:
1. b and c are long. in Java they are 8 bytes. in C++ LIMITS.H, long is 4 bytes "#define ULONG_MAX 0xffffffffUL /* maximum unsigned long value */"
But why time value shows that huge number?
2. It is strange to get small time after running, the currentTimeMillis() return the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.
It took me whole day but I couldn't get answer yet. Do you have some idea?
Thanks

Im not quite sure what your asking here ?????
One thing I would like to point out is that you have youre vars a bit mixed in the subtraction
long b= System.currentTimeMillis();
System.out.println("after time="+b);
c=c-b;
System.out.println("run time="+c);should be
c= b-c which would equal:9345
aproximately 9 seconds...
the currentTimeMillis() return the difference, >>measured in milliseconds, between the current time >>and midnight, January 1, 1970 UTC, Im not too sure this is correct the way you have it stated....
Its better stated that currentTimeMillis() returns the number of milliseconds that have elapsed, at this current time, since midnight, January 1, 1970 UTC, which is a rather large number..Do the math if youd like.....
A time yesterday will be smaller than a time today...
Unfortunately you will need to state your question a bit better in order to get an adequate answer, Please do so and Im sure youll get some answers...

Similar Messages

  • System.currentTimeMillis() going backwards!!!

    Hi,
    The following program runs a loop, each iteration measuring the time, and ensuring the new time is later than the last measured time.
    I run it like this:
    java -cp . Test 500 1
    My JVM is this:
    ahl84:/nfs/ahl16/users/is/djepson/work/backwards $ java -version
    java version "1.3.1.01-release"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.1.01-release-010816-12:37)
    Java HotSpot(TM) Server VM (build 1.3.1 1.3.1.01-release-010816-13:34-PA_RISC2.0 PA2.0, mixed mode)
    On one of our production machines, this program actually reaches the ERROR line - i.e. time is SEEN to go backwards.
    The problem also happens (although less frequently if I use a 0 for the sleep value - i.e. I am not forcing rescheduling on the main thread.
    Please, anyone any ideas???
    The machine in question has 2 CPUs if thats any help, but I can run it on other multi-CPU machines, seemingly without problem.
    public class Test
       public static void main( String[] args )
          for ( int i = 0; i < args.length; i++ )
             System.out.println( "arg[" + i + "]=[" + args[i] + "]" );
          if ( args.length != 2 )
             System.out.println( "Usage:" );
             System.out.println( "java -cp . Test [iterations] [delay (ms)]" );
          else
             Integer iterations = Integer.valueOf( args[0] );
             Integer delay = Integer.valueOf( args[1] );
             Test t = new Test( iterations.intValue(), delay.intValue() );
             t.go();
       public Test( int iterations, int delay )
          _iterations = iterations;
          _delay = delay;
          _errors = 0;
          _lastTime = System.currentTimeMillis();
       public void go()
          System.out.println( "START : Iterations=[" + _iterations + "], delay=[" + _delay + "], time=[" + _lastTime + "]" );
          for ( int i = 0; i < _iterations; i++ )
             long now = System.currentTimeMillis();
             if ( now < _lastTime )
                System.out.println( "Time sequence ERROR, i=[" + i + "], last=[" + _lastTime + "], now=[" + now + "]" );
                _errors++;
             else
                System.out.println( "Time sequence OK,    i=[" + i + "], last=[" + _lastTime + "], now=[" + now + "]" );
                _lastTime = now;
             if ( _delay > 0 )
                try
                   Thread.currentThread().sleep( _delay );
                catch ( InterruptedException e )
                   e.printStackTrace();
          System.out.println( "FINISH : Time=[" + _lastTime + "] errors=[ " + _errors + " / " + _iterations + " (" + ((float)_errors / (float)_iterations * 100) + "%) ]" );
       long _lastTime;
       int  _iterations;
       int  _errors;
       int  _delay;

    I think You may be running into an os/hardware problem. The
    System.currentTimeMillis() returns the number of milli secs since
    sometime in 1970. However the actual resolution of it depends on the operating system and hardware. Its possible that the thread is being
    allcoated to different procs on your machine (after sleeps especially
    and sometimes anyway) and the OS call used by java returns different
    values.
    for some reason I have a hunch that this isn't a java problem as such.
    maybe os/ maybe hardware/ maybe interation of java with both.
    try forcing the VM to run on one processor only.
    matfud

  • Does System.currentTimeMillis() cater for daylight saving

    My question is does System.currentTimeMillis by any means cater for the daylight savings time or in the other case when clocks are moved backwards it repeats it self???????
    Its pretty confusing isnt it?

    the whole problems with the currentTimeMillis is that it calculates the offset from the System clock - System TimeZone Offset
    if the System uses Manual DST or the auto DST is not checked (Windows)
    The the user of the system changes manually the clock and the calculation
    current millis will be wrong one hour
    for example I am in GMT + 2 + DST(1)
    GMT is 1200
    Local OS shows 1400, and I manually change it to 1500 (DST check box is not checked
    the Java will report GMT time 1300 (1500 - 2:00)
    whic is wrong.
    There is no indication wether this check box is checked or not
    If anyone knows how to find out if its checked please tell all

  • Truncate System.currentTimeMillis()

    I'm using System.currentTimeMillis() for a timestamp. I want to truncate the default 13 digits to 10. Any ideas?
    Thanks.
    tahub

    Another question might be WHY?
    Why not simply store the entire thing as it is (a long) and it'll
    only be 4 bytes instead of 10?
    But, if you want the right -most digits dropped, simply divide it.int iSeconds = System.currentTimeMillis() / 1000L;

  • System.nanoTime X System.currentTimeMillis

    Hi,
    i`ve been trying to make some measurments in my app without the use of any other specializes tool like optimizer, so i`m trying to hear as many opinios i can (as someones my noticed, i`ve posted some similar questions on this topic).
    I did make a test in my windows XP and got the precision of System.currentTimeMillis() around 15 ms, but i need a more accurate measurment. I know the j2se 1.5 has a System.nanoTime() function wich gives nanoseconds measurment.
    However, before i download, install and reconfigure my system`, i`d like to hear some opinions.
    If i use System.nanoTime(), i`ll get the time in nanoseconds, but will the ERROR average (or the accuracy) be the same as with System.currentTimeMillis() ???
    Cause if i have a method that takes 1500 ms (MILIseconds) or 1500000 ns (NANOseconds) and the precision o my system still be 15ms (MILIseconds) i`d wouldn`t be helpfull, right!
    So, can i get some opinions?!
    Thanks,
    ltcmelo

    >
    well... it was my understanding that Windows has the
    capability, but you have to enable it somehow, cuz
    it's not enabled by default. That could be wrong, as
    I'm not a Windows programmer. But I've never seen
    Java give better then 10 ms precision on any Windows
    system.Not that I know about..
    From a December 1997 MSJ Article "Under the Hood"....
    Before I get to the benchmarking code and, more importantly, the results, let me say a few things about my efforts to make the timings reliable. I used the QueryPerformanceCounter API, which provides timings at the microsecond level. According to the QueryPerformanceFrequency API, the performance counter increments 1.19 million times a second, a number that corresponds to one of the traditional timers found on x86-based systems. To prevent the numbers from being skewed by too few samples, I executed the APIs 50,000 times in a loop.
    Looking at the code I didn't seen anything that suggested that it was being enabled.
    The API is available back to 95 and NT.
    MIght be something newer but I use a 2000 version of MSDN (they switched formats after that and made it unusable.)

  • System.currentTimeMillis();

    Hi,
    here is some code:
    System.out.println("A:"+System.currentTimeMillis());
                             System.out.println("Deg:"+deg);
                             tuple t=new tuple(deg, systime);
                             System.out.println("B:"+System.currentTimeMillis());which leads to the following output:
    Deg:44.0
    B:1008942953100
    A:1008942953100
    Deg:49.0
    B:1008942953100
    A:1008942953100
    Deg:35.0
    B:1008942953160
    A:1008942953160
    Deg:37.0
    B:1008942953160
    A:1008942953160
    Deg:40.0
    B:1008942953160
    A:1008942953160
    Deg:44.0
    B:1008942953160
    A:1008942953160
    Deg:49.0
    B:1008942953160
    A:1008942953160
    Deg:35.0
    B:1008942953210
    A:1008942953210
    Deg:37.0
    B:1008942953210
    A:1008942953210
    Deg:40.0
    B:1008942953210
    A:1008942953210
    Deg:44.0
    B:1008942953210
    A:1008942953210
    Deg:49.0
    B:1008942953210
    A:1008942953210
    Deg:35.0
    B:1008942953210
    A:1008942953210
    Deg:37.0
    B:1008942953210
    A:1008942953210
    Deg:40.0
    B:1008942953210
    A:1008942953210
    Deg:44.0
    B:1008942953270
    FF Detected.
    Question:
    Why do i have ten times the same number? Their is no explanation for this "jump".
    Does the System.currentTime... command provide real millisecond accuracy on Windows?
    Does someone know something about this?
    Sascha

    Hi,
    i talked about this with my local team (three psychologists, waiting for a proper eye tracker software) ...
    we came to this conclusion:
    Prerequisite:
    the prior stated routine is DIRECTLY called upon receiving data from the serial port and creates a new touple (deg being the degrees of the eye movement, systime being the system's reference time upon invocation).
    solution a:
    the data comes in blocks of 4-8 doublebytes AND java is as quick as doing more than 1000 lines of code (explicit the LOCs of java native library code) in less than 1 ms
    solution b:
    the data comes in blocks of 4-8 doublebytes AND Java does 1000 lines of code in a time frame as big as approx. 50-60 ms, rounding the system time in milliseconds
    solution c:
    the data comes in doublebyte blocks not at once but with 5 to 10 ms delay in between and java rounds.
    I have FIFO enabled, set to (16) ... don't know what this 16 means .... May be FIFO buffers these bytes and releases these at once ...
    I personally prefer solution B, i can't believe JAVA is as fast as stated in solution A (beside the fact that i don't do anything else which could result in a 50 ms leap)
    Sascha

  • Any1 know how 2 use System.currentTimeMillis()?

    System.currentTimeMillis()%16?

    System.currentTimeMillis()%16?That would give you a number between 0 and 15, based on the time.
    Is that what you want (if so, why?)
    What do you want to do? What is your question?

  • Monotonicity of System.currentTimeMillis ()

    Hallo,
    a short question: Does the JVM guarantee that the system time returned by System.currentTimeMillis () is monotonic, i.e. the value returned always greater or equal to the value returned eariler? I assume not.
    The background: I'm writing a server that requires this property. The host machine is a Unix server that uses an NTP service to synchronize its clock regularly. Therefore it is possible that the system clock is reset to an earlier time, violating the described property. I wonder whether I have to personally take care about this or not.
    TIA

    This simple program...public class test{
      public static void main(String args[]){
        long lastTime = 0;
        long currentTime = 0;
        while(lastTime <= currentTime){
          try{ Thread.currentThread().sleep(1000); }
          catch(InterruptedException e){}
          lastTime = currentTime;
          currentTime = System.currentTimeMillis();
          System.out.print(".");
    }... on a computer with an NTP client did indeed terminate when the system time was moved back. In other words: System.currentTimeMillis() is not monotonous.
    /Michael

  • I need to delete my Apple ID on my iPhone 4.  I forgot my psw for my account.  When I answer the security question, the system responds incorrect answer.  I created a new Apple iTunes account but I still unable to delete the old iTunes account.

    I need to delete my Apple ID on my iPhone 4.  I forgot my psw for my account.  When I answer the security question, the system responds incorrect answer.  I created a new Apple iTunes account but I still unable to delete the old iTunes account.

    AppleFAN7591 wrote:
    I need to delete my Apple ID on my iPhone 4.  I forgot my psw for my account.  When I answer the security question, the system responds incorrect answer.  I created a new Apple iTunes account but I still unable to delete the old iTunes account.
    How to reset your Apple ID password.
    Go to iforgot.apple.com and type in your Apple ID, then click 'Next'.
    Verify your date of birth, then click 'Next'.
    You'll be able to choose one of two methods to reset your password, either E-Mail Authentication or Answer Security Questions.
    If neither method works, then go to https://getsupport.apple.com
    (If you see a message that says 'There are no products registered to this Apple ID, simply click on 'See all products and services')
    Choose 'More Products & Services', then 'Apple ID'.
    A new page will open.
    Choose 'Other Apple ID Topics', then 'Lost or forgotten Apple ID password'.
    Click the blue 'Continue' button.
    Select the contact option that suits your needs best.
    How to reset your Apple ID security questions.
    Go to appleid.apple.com, click on the blue button that says 'Manage Your Apple ID'.
    Log in with your Apple ID and password. (If you have forgotten your Apple ID password, go to iforgot.apple.com first to reset your password with a password recovery email)
    Go to the Password & Security section on the left side, and click on the link underneath the security questions that says 'Forgot your answers? Send reset security info email to [email]'.  This will generate an automated e-mail that will allow you to reset your security questions.
    If that doesn't work, or  there is no rescue email link available, then click on 'Temporary Support PIN' that is in the bottom left side, and generate a 4-digit PIN for the Apple Account Security Advisor you will be contacting later.
    Next, go to https://getsupport.apple.com
    (If you see a message that says 'There are no products registered to this Apple ID, simply click on 'See all products and services')
    Choose 'More Products & Services', then 'Apple ID'.
    A new page will open.
    Choose 'Other Apple ID Topics', then 'Forgotten Apple ID Security Questions'.
    Click the blue 'Continue' button.
    Select the contact option that suits your needs best.

  • Converting value from System.currentTimeMillis() to readable format

    hi
    i have in database coumn with values that were stored as result of executing System.currentTimeMillis() in java (=“the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC). i need to convert these values to some human readable format.
    i am able to get year, month and day from these values(value_date) in format "dd/mm/yyyy" but i need hours, minutes and seconds as well.
    select i have for getting years, months and days:
    select (
    extract (day FROM (to_date('01/01/1970 00:00:00000','mm/dd/yyyy hh24:mi:sssss') + value_date/1000/86400))
    || '/'||
    extract (month from (to_date('01/01/1970 00:00:00000','mm/dd/yyyy hh24:mi:sssss') + value_date/1000/86400))
    ||'/'||
    extract (year FROM (to_date('01/01/1970 00:00:00000','mm/dd/yyyy hh24:mi:sssss') + value_date/1000/86400))
    FROM some_table;
    please advice how to improve this select to get something like "dd/mm/yyyy hh:mm:ss"
    thanks

    Note that the result with to_char might still not be what you expect (due to timezone and/or DTS):
    SQL>  CREATE OR REPLACE FUNCTION currenttimemillis
       RETURN NUMBER
    IS
       LANGUAGE JAVA
       NAME 'java.lang.System.currentTimeMillis() return java.lang.long';
    Function created.
    SQL>  select to_char(sysdate, 'dd.mm.rrrr hh24:mi:ss') dt,
           to_char(date '1970-01-01' + currentTimeMillis/(1000*24*60*60),'dd.mm.rrrr hh24:mi:ss') dt2
      from dual
    DT                  DT2               
    04.06.2009 16:44:09 04.06.2009 14:44:09

  • System.currentTimeMillis() problem in Solaris

    hi all
    I have one problem, I have one aplicantion transactional development in java runing in win Nt that up 3 console different + 1 registry console. I have that save the transaction's date in the DB when begin transaction and end transaction. In win NT with Timestamp(System.currentTimeMillis()) is OK. Now in Solaris when up the 3 console, in one, Timestamp(System.currentTimeMillis()) show me the correct time(the time set in the server), but in other console show me other time different (six hour +) and I don't know where takes out this time. I saw the server's timezone and it's ok, and I do in one console >date show me the correct time.
    Anyone help me?
    More information:
    Solaris 8

    Huh?
    currentTimeMillis() returns a number so I can only suppose that on one machine the number is significantly different than on another.
    That means that the times on the machines (nothing to do with java) are different.
    If however you are using Date() to create and display a time, then it means the timezones are different (again nothing to do with java.)

  • Nokia 6030 and System.currentTimeMillis

    Hi
    I'm developing my game for J2ME phones. It works well on a lot of devices. Today I got Nokia 6030 (S40 2nd Edition) and tested my game on this phone. It very strange! Timer works veeeery fast. I made small debug on screen. I made drawString System.currentTimeMillis() and I saw that time goes very fast. On all phones System.currentTimeMillis() increases 1000 per second. On 6030 System.currentTimeMillis() increases 1000000 (or more) per second. Why?!?! On emulator of Nokia 6030 it works well (1000 per second). It very strange. I tested this program on a lot of devices and everywhere it worked well.
    Help me, please...
    MDW

    could be a bug, someone accidentally putting tree zero to much in their code...

  • System.currentTimeMillis() returns time in UTC or not??????

    Hello Friends,
    I want to know that "System.currentTimeMillis()" returns time in UTC or Current Local time
    ie suppose i set my TimeZone (GMT+ 2)
    then statement gives me value in milliseconds by adding 2 hours to the GMT(Is this value should consider as UTC time or we have to subtract and add offset value according to the timezone.
    If time value return by statement is in local time and this is not UTC then is there is any provision in Java to convert local time into UTC time ??
    Regards
    Gaurav

    ejp wrote:
    It returns 'the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.'.Which, of course, as I have tried to explain to the OP (but seemingly not very well) that the "current time" referenced must also be the "current time" in UTC. If the starting point is UTC the ending point is UTC (otherwise it doesn't make any sense to measure it that way). I also attempted to tell him that, when he outputs a String representation of that time (i.e. toString or with a DateFormat Object) that the time he sees will be the time according to the TimeZone set in the DateFormat object, or the local timezone when using toString. But, as mentioned, Date objects (and so, essentially, the long value) is always UTC (relevant to the starting point, of course).
    A quote from the Date Class
    Although the Date class is intended to reflect coordinated universal time (UTC), it may not do so exactly, depending on the host environment of the Java Virtual Machine.which I take to mean that Date is always UTC in so far as the host environment is capable of it.

  • Help with code for System.currentTimeMillis()

    I need to time how long it takes to do various sorts (selection sort, insertion sort) and was instructed to use System.currentTimeMillis() to accomplish this. Please take a look at the code below and let me know what is wrong. I can get the file to complile but it does not record the time it takes to run the sorts. I'm pretty sure my error is in the below section of code. In order to save space, I've only pasted the snippit of code for this particular function. Let me know if I need to paste more code. Thanks in advance.
    case 5:
                             System.out.print("Enter the value to look for: ");
         val = scan.nextInt();
         time1 = System.currentTimeMillis();
         loc = list.linearSearch(val);
         time2 = System.currentTimeMillis();
                             totalTime = time1 - time2;
                             System.out.println("Total time for this search is: " + totalTime);
         if (loc != -1)
                                  System.out.println("Found at location " + loc);
         else
                                  System.out.println("Not in list");
         break;
                             

    It could be that it isn't actually doing anything
    though. Either because the data is poorly choosen or
    because it isn't actually sorting due to a bug.The name of the method being timed is "linearSearch". That's a really poor name for a method that is supposed to be sorting. But from other aspects of the code I would guess that it is doing a linear search of an array, looking for a particular integer. Even if the integer isn't in the array, comparing 20,000 integers is a trivial exercise.
    People don't realize just how long a millisecond is for a computer. If you have a 1 GB processor (not uncommon these days) then you can do one billion (one thousand million) operations per second. That's one million operations per millisecond. So chances are, even realizing that there's a whole lot of overhead in a high-level language, the OP's code runs in less than 1 millisecond.

  • System.currentTimeMillis() not accurate on Windows ?

    Hi,
    JVM : 1.4.2_03-b02
    OS : Windows XP
    processor : XEON 2.4 GHz
    Following test fails with 62.5 error percentage.
    Is it due to windows failing to give time on a millisecond level ?
    Or is there another reason ?
      public void testSleep() throws Exception {
        int total = 1000;
        int errors = 0;
        for ( int j = 0; j < total; j++ ) {
          long start = System.currentTimeMillis();
          Thread.sleep(5);
          long end = System.currentTimeMillis();
          if ( end < start+5 ) {
            errors++;
        Float errorPercentage = new Float( errors*(float)100/total );
        assertEquals( new Float(0), errorPercentage );
      }Regards, Tom.

    The millisecond level of precision is only a possibility provided by the API, the OS does not forcibly provide it.
    But Thread.sleep will not be absolutely precise, it is the most likely culprit.

Maybe you are looking for