Thursday, March 31, 2011

Print Epoch Time in Different Languages

As you may know, tonight, at exactly 23:31:30 UTC, Epoch Time will reach 1234567890! Hurray!

One way of watching epoch time is by using Perl:

perl -le 'while(true){print time();sleep 1;}'

Can you do the same in another programming language?

From stackoverflow
  • java:

    System.out.println((new java.util.Date(0)).toString());
    

    That's the epoch :) ... the current time would be:

    System.out.println((new java.util.Date()).toString());
    

    For getting the amount of milliseconds passed since the epoch, do:

    System.out.println("" + (new java.util.Date()).getTime());
    
    dogbane : This prints the Epoch (a specific moment in time), not "Epoch Time" which is the time elapsed since 1 January 1970 00:00:00. The output of your program does not match mine.
  • This would be the same code in c#:

        DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0);
        while (true)
        {
            Console.WriteLine((int)(DateTime.UtcNow - epoch).TotalSeconds);
            Thread.Sleep(1000);
        }
    

    And like tehvan said, it's the current time, not "Epoch" time

    dogbane : Epoch Time is the time elapsed since 1 January 1970 00:00:00
  • Java

    import java.util.Date;
    
    public class EpochTime {
        public static void main(String[] args) {
            while (true) {
                System.out.println(new Date().getTime() / 1000);
                try {
                    Thread.sleep(1000);
                }
                catch (InterruptedException ignore) {
                }
            }
        }
    }
    
  • shell script:

    while :; do printf "%s\r" $(date +%s); sleep 1; done
    

    python:

    import time
    import sys
    
    while True:
        sys.stdout.write("%d\r" % time.time())
        sys.stdout.flush()
        time.sleep(1)
    
  • python one-line:

    python -c "while True: import time;print time.time();time.sleep(1)"
    
  • php one-liner

    php -r 'while(true) { echo time(), "\n"; sleep(1);}'
    
  • this site is in my favorites and has many answers for it

0 comments:

Post a Comment