How does java.util.Date.getTime method convert a given date & time into long number?
Java API documents say that - "Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object."
Appreciate any help.
Check out the Date.java source code.
You'll see that in the simplest case, the Date object stores the number of milliseconds since 1970, rather than the date/time etc.
Actually, despite the apparently unambiguous definition in the Java API doc, it is interesting to note that the number of milliseconds reported is not the actual number of physical milliseconds, or seconds for that matter, that have elapsed since January 1st 1970 00:00:00 GMT. It is really the number of physical seconds plus the number of leap seconds that have been artificially inserted.
Related
I'm looking for the name of the standard for time, represented in milliseconds since midnight January 1, 1970 UTC. We can get one calling System.currentTimeMillis() in Java. For example when we are talking about the same time, represented in seconds - we use term Unix time. It would be great if you provide a link to standard in the answer.
In the GNU Linux documentation it is called:
seconds since the epoch
Extrapolating you could call it milliseconds since the epoch.
I have one simple question. How to achieve this format of date 1438117140000+0300. First part 1438117140000 its the time in millisec , that i convert with no problem, second part with timezone info is my headache , how to get it ??
You can use String.format for this purpose:
Date now = new Date();
System.out.println(String.format("%tQ%tz", now, now));
Executing the code just printed out this:
1438635740416+0300
The conversions for date/time are specified in the documentation. Here, I've used the following two conversion characters:
'Q': Milliseconds since the beginning of the epoch starting at 1
January 1970 00:00:00 UTC, i.e. Long.MIN_VALUE to Long.MAX_VALUE.
'z': RFC 822 style numeric time zone offset from GMT, e.g. -0800. This
value will be adjusted as necessary for Daylight Saving Time. For
long, Long, and Date the time zone used is the default time zone for
this instance of the Java virtual machine.
It looks like +0300 means +3 hours from GMT. so convert 0300 (3 hours) to milliseconds and add to 1438117140000. then convert to a date time as you are already
Split the value you have to '+' then add 3 hours as miliseconds to the first value of the array that split method returned.
The date in database is 2012-03-20 12:24:34.123456. We need to display it in long format.so, we used getTime() method. But when we are converting back to date again, the nano seconds are not matching exact precision. The date after conversion is 2012-03-20 12:24:34.123. last 456 is missing. any one help to get exact date with nano seconds.
From javadoc
java.util.Date, getTime(), returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object. 456 is missing because is less than millisecond, is microseconds
You can use getTimestamp() instead of getTime(). The java.sql.Timestamp object returned, when treated like a java.util.Date, has integer seconds. By calling getNanos() on it, you can get the fractional seconds in nanoseconds.
As part of some logic, it is necessary in my program to turn a long Java timestamp (including year, month, etc.) to a 'short' Java time. This should correspond to exactly the same hours, minutes and seconds of the original time, but within 1 day of Jan 1 1970 (i.e. a value between 0 (00:00:00) and 86400000 (23:59:59)). An example is the conversion in the question.
In order the perform this, I thought the below code would work:
public int convertToTime(long fullTimeStamp) {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(date);
c.set(Calendar.DATE, 1);
c.set(Calendar.MONTH, 0);
c.set(Calendar.YEAR, 1970);
return (int) c.getTimeInMillis();
}
The issue I am having is to do with timezones. In the UK we are currently in BST. After setting all the values with the function, the time remains the same numbers (e.g. 8.00am) but changes the timezone to GMT! 8.00am GMT is of course not the same as 8.00am BST, and is instead equal to 9.00am BST.
Adding some console output to the function demonstrates this issue:
public int convertToTime(long fullTimeStamp) {
System.out.println(new Date(fullTimeStamp)); // correct
Calendar c = Calendar.getInstance();
c.setTimeInMillis(fullTimeStamp);
System.out.println(c.getTime()); // correct
c.set(Calendar.DATE, 1);
c.set(Calendar.MONTH, 0);
c.set(Calendar.YEAR, 1970);
System.out.println(c.getTime()); // incorrect!
return (int) c.getTimeInMillis();
}
Program output:
Wed Jun 19 12:15:00 BST 2013 // ok
Wed Jun 19 12:15:00 BST 2013 // this makes sense
Thu Jan 01 12:15:00 GMT 1970 // Calendar, stahp!
The desired behaviour is for the last part to read:
Thu Jan 01 11:15:00 GMT 1970
or
Thu Jan 01 12:15:00 BST 1970
Is this expected behaviour of the calendar? My understanding was that it keeps all the 'digits' the same that aren't modified, so if the value of HOUR_OF_DAY is 8, it should stay at 8, even if the timezone is modified.
I have tried setting the timezone on the calendar (before any values are set) to BST and GMT and exactly the same behaviour occurs. I also cannot manually add or remove milliseconds to delete all years after 1970 as I will have to handle leap years.
Aside from 'use Joda time (or some other time package)' does anyone have any other suggestions to perform this operation? I kind of need to get a quick fix in before experimenting with other packages if possible.
Thanks!
I think you're running foul of a little-known fact about the UK time zone: at the Unix epoch, we were actually in UTC+1. Java is getting the time of day right (within the UK time zone), but the name wrong - it shouldn't be specifying GMT, but BST. This isn't BST as in British Summer Time; it's BST as in British Standard Time. Yes, it's that mad.
From the relevant wikipedia article:
An inquiry during the winter of 1959–60, in which 180 national organisations were consulted, revealed a slight preference for a change to all-year GMT+1, but the length of summer time was extended as a trial rather than the domestic use of Greenwich Mean Time abolished.[8] A further inquiry during 1966–67 led the government of Harold Wilson to introduce the British Standard Time experiment, with Britain remaining on GMT+1 throughout the year. This took place between 27 October 1968 and 31 October 1971, when there was a reversion to the previous arrangement.
It's worth bearing in mind that your original problem statement is somewhat ambiguous: you're taking in a long, which is just the millis since the Unix epoch - but then you're trying to interpret it in terms of the hour of day, which immediately begs the question of which time zone you need to interpret it in. Have you made that decision? If so, you should document it very carefully, and make sure your code complies with it.
Ultimately, my recommendations are:
If you can possibly use Joda Time, do so. It will save you hours and hours of heartache.
If you're trying to calendar calculations like this, consider changing the time zone of the calendar to UTC before doing anything else; it will save you some heartache
Avoid using Date.toString() where possible - you could use a DateFormatter with the time zone set to UTC, and then you would see the expected results
As user2340612's answer states, to get just the "millisecond of UTC day" you can use simple arithmetic - but not quite with the values given. I would use:
long timeOfDay = millisecondsSinceUnixEpoch % TimeUnit.DAYS.toMillis(1);
... but this only works if you're interested in the UTC time of day for the given instant. (It will also give a negative result for negative input, but you may not care about that.)
If you need a timestamp between 0 and 86399999 (which is 23:59:59.999) you can get the current timestamp and calculate the remainder of the division between it and 86400000:
desired_time = cur_time % 86400000
But you'll miss the summer time, if present.
I have a timestamp object and need to get the milliseconds from it, can someone help me with an example code snippet ?
You can use Timestamp.getTime()
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
represented by this Timestamp object.
Example:
long timeInMilliSeconds = t.getTime();
// do magic trick here
Note: Timestamp is extend from Date.
You can just call getTime() to get milliseconds since the Unix epoch. Is that what you were after, or did you want "milliseconds within the second" or something similar?
Note that using just milliseconds is slightly odd for a Timestamp, given that it's designed specifically to be precise to the nanosecond. So you should usually be using getTime() in conjunction with getNanos().
From the Java Docu (link):
public long getTime()
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Timestamp object.
I guess this will give the output you want.
public void timeInMills(Timestamp t){
System.out.println("Time in Milli second "+t.getTime());
}