how can i fetch current date and time of my system in java without using any predefined classes or libraries?
-
02-07-2021 - |
문제
how can i fetch current date and time of my system in java without using any predefined classes or libraries? i am actually making a Date ADT of my own from scratch as java.util.Date or Java.util.Calendar. but i am not able to find out a way to fetch system date and time, say to calculate age of somebody if he enters his current age. in a way i want to learn how they developers of Date or Calendar class actually implemented it. is there a way that i can see the code of Date and Calendar classes defined in java.util package.
해결책
Using System.currentTimeMillis():
Returns the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.
As for the source code of java.util.Date
and java.util.Calendar
, you can either download the source directly from http://jdk7.java.net/source.html, or view it online in docjar.com
or here.
다른 팁
Well System.currentTimeMillis()
isn't in java.util
- is that what you were looking for? You'd then have to write the code to work out what that value (milliseconds since the unix epoch) means in terms of years etc - and you should consider the time zone and calendar system.
I would personally avoid trying to write your own date/time package unless it's just for fun. java.util.Date
/ Calendar
are awful, but Joda Time is much better, and there's the upcoming JSR 310.
Is there a way that i can see the code of Date and Calendar classes defined in java.util package.
Sure - when you installed the JDK, you should have had the option of also installing a copy of the source code for the standard libraries, typically in src.zip
. Alternatively, you could go to openjdk.java.net and look there.
actually i don't want to use any predefined function at all.
Then you'd have to use JNI to get to an underlying system call, which seems pretty pointless to me - as it's basically what System.currentTimeMillis
will do. That's fine if you're trying to learn JNI, but it's not really got much to do with date/time.
Of course if you're interested in an accurate time instead of the *system time, you could implement an NTP client.