Calendar getTimeInMills = July 4, 46452? - java

I am using Calendar on a Samsung Note. If I get a new instance of Calendar with Calendar.getInstance() and then call getTimeInMills() without doing anything else I get 1403732346277, which apparently is some value in the very far future.
I need to get a unix style timestamp. Is there some other preferred way to do this? Or some reason why the Calendar is returning this value (i.e. a standard adjustment I can make)?

Unix time represents the number of seconds from the epoch. As the name implies, getTimeInMillis() will return the number of milliseconds from the epoch. You need to divide your milliseconds by 1000 to get unix time.
long unixTime = Calendar.getInstance().getTimeInMillis() / 1000;

getTimeInMillis() returns you the time difference from Jan 1, 1970 with the calendar time in milliseconds.
Here is the calculation:
1403732346277 ms = 1403732346.277 seconds
1403732346.277 s = 389925.6517... hours
389925.6517 h = 16246.90 days
16246.90 days = 44.512 years (simple calculation: I divided by 365 just to get an approx idea. There are leap years in between.)
If you find the difference of current date from Jan 1, 1970, it is 44 years and ~6 months. So it seems to be giving you right time in milliseconds.

Or some reason why the Calendar is returning this value (i.e. a standard adjustment I can make)?
The java.util.Calendar API stores dates and times as the number of milliseconds that have elapsed from epoch (January 1, 1970 midnight UTC).
The number you got from Calendar.getInstance() - 1403732346277 - is what you'd expect. It's the number of milliseconds from epoch up to today at the exact time you called Calendar.getInstance().
If you want to extract more human-readable date/time information from that Calendar object, you can do something like:
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minutes = cal.get(Calendar.MINUTE);
I need to get a unix style timestamp. Is there some other preferred way to do this?
As this post points out, you can get UNIX epoch by:
long unixTime = System.currentTimeMillis() / 1000L;

Related

How can I get date, time and day from open weather API in android [duplicate]

This question already has answers here:
Unix epoch time to Java Date object
(7 answers)
Closed 4 years ago.
I am trying to get a date, time and day from open weather API of a specific location and specific day using latitude and longitude. But it gives me a long integer something like this 1525974999. How can I retrieve date time and day from this?
Using Java 8 Time API:
Instant.ofEpochSecond(1525974999) // returns: 2018-05-10T17:56:39Z
Using old Java Date:
new Date(1525974999 * 1000L) // returns: Thu May 10 13:56:39 EDT 2018
I'm in Eastern US time zone
The integer represents the amount of time it has been passed since January, 1, 1970. (Unix Time Stamp)
You can use a converter from unix time stamp or just do the math programmatically.
It's probably in seconds. Try this:
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timeReturnedByAPI * 1000);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
Here is the Calendar API: https://developer.android.com/reference/java/util/Calendar
Edit: You may want to use the version of getInstance that takes a time zone to get the local time.
Edit 2: Updated in response to comments.

Round date long value

In my Java project I used date in long and for example it is 12136219 and by creating Date object as below:
long time = 12136219;
Date date = new Date(time);
and it represent date as Thu Jan 01 04:22:16 CET 1970. How can I round date (in long representation) to minutes ?
For example I want achieve Thu Jan 01 04:22:00 CET 1970 if the seconds are <30 and Thu Jan 01 04:23:00 CET 1970 if the seconds are >=30 but I want round this long time = 12136219 representation. Any idea?
Don’t reinvent the wheel. Use java.time.Instant for representing an instant in time:
Instant i = Instant.ofEpochMilli(time);
i = i.plusSeconds(30).truncatedTo(ChronoUnit.MINUTES);
Instant doesn’t offer rounding, only truncation. However, adding 30 seconds and then truncating gives you what you want. If you need your milliseconds back, it’s easy:
time = i.toEpochMilli();
System.out.println(time);
With the number from your question this prints
12120000
(This is equal to an instant of 1970-01-01T03:22:00Z, or 1970-01-01T04:22+01:00[Europe/Paris] in CET, or the expected rounding down of your 04:22:16 CET.)
PS I am quite convinced that a library like Time4J will offer rounding so you don’t need the trick of adding and truncating. Unfortunately I don’t have the experience to give you the details.
Since time is
"milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT"
You could calculate the seconds like this:
secondsInMillis = time % (60 * 1000) //get remainder (modulo): seconds * milliseconds
if (secondsInMillis < 30000) {
time -= secondsInMillis; //round down
} else {
time += (60000 - secondsInMillis); // round up
}
When you create a Date from a long, the long represents the number of milliseconds since Jan 1, 1970. There are 60*1000 milliseconds in a minute. That should be enough information to fashion the rounding algorithm you need.
Reset seconds and milliseconds with Calendar.set
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.MINUTES, calendar.get(Calendar.SECOND) >= 30 ? 1 : 0)
currentDate = cal.getTimeInMillis();
Sets the given calendar field to the given value. The value is not interpreted by this method regardless of the leniency mode.
You should do it on the Date object. There is no easy way to calculate it in the time epoch, because of various difficulties including the length of a month (28, 29, 30 or 31).

How to calculate time difference considering day light saving?

I have function which calculated time difference between two dates in milliseconds. I am getting the time just before 1 hour of day light saving starts and then calculating time after 5 minutes of it. I is giving me 5 minutes of difference, One hour getting skipped. Do anyone having idea?
Just use this:
Suppose date1 is 20.03.2016, 13:00
date2 is 21.03.2016, 17:00
Calendar cal1 = Calendar.getInstance();
cal1.set(Hour_of_day,13);
cal1.set(Calendar.DAY_OF_MONTH, 20);
Calendar cal2 = Calendar.getInstance();
cal2.set(Hour_of_day,17);
cal2.set(Calendar.DAY_OF_MONTH, 21);
then difference of two gives time in milliseconds.
long time_in_milli = cal2.getTimeInMillis()-cal1.getTimeInMillis();
This would already take into account the day light saving thing.
I solved this by including timezone with date ex: Format your date with timezone like - "yyyy-MM-dd'T'HH:mm:ss.SSSZ" and then calculate time difference.

Finding the day in seconds since epoch, modulus not working

I have the following code to try and get the current day in seconds since epoch, by removing any seconds after 00:00:00 on any given day:
public void method(Date date) {
...
long dayDate = date.getTime() - (date.getTime() % 86400L);
...
}
For some reason, dayDate is simply being set to date.getTime(), and the mathematical operators are doing nothing here.
How would I go about fixing this?
I'll recommend that you use Joda Time library. It has most of the functions related to date, time and calendar that you'll ever need.
Like Ignacio already pointed out, date.getTime() returns the number of milliseconds since January 1st, 1970, so your line should have been:
long dayDate = date.getTime() - (date.getTime() % 86400000L);
Iif you are planning on creating a new Date with dayDate, make sure that it has the right timezone, e.g. it should be in the UTC/GMT timezone. Otherwise, strange things like this could happen:
Date epoch = new Date(0);
System.err.println(epoch);
which gives on my machine Thu Jan 01 01:00:00 CET 1970 because my dates are by default created in the CET (+1) timezone. So if you would use your code and you would create a new Date instance by using the long you calculated, you would end up with a date not at 0:00 on that day, but at 1:00.
However, without immediately resorting to Joda Time (which may not be an option in your project), you can use a Calendar to get the number of seconds:
// Create the calendar and set the date.
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
// Set the hours, minutes, etc. to 0.
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
long dayDate = calendar.getTime();

How to define the date format?

I have the int number 2455449 and I know that represents the date 09/09/2010. How can I define the date format wihch is used? I need to generate a new date in this format. It will be used for http requests. I suppose that is Julian but I'm not sure. I tried to convert this number to the date but it didn't return the right date of 09/09/2010. Probably I used a wrong SimpleDateFormat("mm/dd/yy") or Calendar.XXXX (e.g.Calendar.DAY_OF_YEAR)
var now = new Date();
now.format("m/dd/yy");
// Returns, e.g., 6/09/07
// Can also be used as a standalone function
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM
// You can use one of several named masks
now.format("isoDateTime");
// 2007-06-09T17:46:21
// ...Or add your own
dateFormat.masks.hammerTime = 'HH:MM! "Can\'t touch this!"';
now.format("hammerTime");
// 17:46! Can't touch this!
http://blog.stevenlevithan.com/archives/date-time-format
looks like an equation with unknown function.f(d,m,y)=D; Where d the day, m month,y year and D is int date. And without loss of generality we can assume that this mapping should be one to one i.e. every valid (d,m,y) combination should map to a unique positive integer (>=0) and every positive integer must represent a valid and unique (d,m,y) tuple.So the most obvious choice of function f (based on the property of dates) is number of days elapsed since the first day, which satisfies our conditions. so now we have boundary condition.f(d1,m1,y1)=0;
f(9,9,2010)= 2455449;where d1,m1,y1 represents the reference date like epoch in unix timestamp. Using the obvious function (see above), (d1,m1,y1) comes out to be (10 5 -4713). So the DatFormat used is number of days elapsed since 10th June 4713 B.C. Approximately.
It is a Julian day number, and it counts the number of days since January 1, 4713 BC Greenwich noon in the Julian proleptic calendar.
To convert from a JD to a unix time stamp:
unix_time_stamp = ( JD -2440587.5) * 86400
To convert from unix time stamp to JD:
JD = (unix_time_stamp / 86400) + 2440587.5
Note that JD is counted from the noon, not midnight. That's why it's .5 at the end of the addition.
Update If you want to use it in javascript (that uses milliseconds since the epoch)
function dateFromJulianDay(julian_day) {
return new Date( (julian_day - 2440587.5) * 86400000);
}
function dateToJulianDay(date) {
// date should be a javascript Date object
// or a variable with milliseconds since the unix epoch 1 jan 1970
return ( date / 86400000) + 2440587.5;
}
console.log(dateFromJulianDay(2455449));
console.log(dateToJulianDay(new Date(2010,9-1,9)));
Remember that the month in the Date constructor is 0-11, whats why I do -1 above.

Categories

Resources