Date.getTime in Android Eclipse - android

Here is my code to assign a value to the Date:
long saveddatevalue = new Date().getTime();
I just want to know, what does this saved long variable actually show? I wish to use this to output values within a certain number of days.
Thanks!

It will basically give you the same result as System.currentTimeMillis() - the number of milliseconds since the Unix epoch of midnight January 1st 1970, UTC.

It is far easier to work with java.util.Calendar.add(int, int) for manipulating dates. Here is some sample code.

Related

Custom the display value of SimpleDateFormat in android

I currently work on a double value that represent the total consumed time
for example, I have a 260 that means 260 second is consumed
To display to user, I would like to format it
for example , it should be something like 0year,0month,0day,1hr,2min,30sec
But I found the SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); is not quite suit my case (seems the "h" in "hr" is conflicted with the hour symbol?)
So , how to change the HH:mm:ss to the case mentioned above?
Thanks for helping
DateFormat is useful to format dates, not an absolute value of time.
To achieve your goal, you can take a look to Formatter
Hope this sample helps you:
String total_consumed_time = String.format("%01d year, %01d month, %01d day, %01d hr, %01d min, %01d sec", time_year, time_month, time_day, time_hour, time_min, time_seg);
I didn't try that code, but I use similar workaround with an absolute time in milliseconds:
long time = 260000; // time in mseg
long time_hour = TimeUnit.MILLISECONDS.toHours(time);
time -= TimeUnit.HOURS.toMillis(time_hour);
long time_min = TimeUnit.MILLISECONDS.toMinutes(time);
time -= TimeUnit.MINUTES.toMillis(time_min);
long time_seg = TimeUnit.MILLISECONDS.toSeconds(time);
String total_time = String.format("%02d:%02d:%02d", time_hour, time_min, time_seg);
With a result of "00:04:20" (4 minutes and 20 seconds).
Accepted answer is in most cases okay for solving your problem, but gives wrong reason why not to use the class SimpleDateFormat. This format class is well suited for objects of type java.util.Date (which are kind of unix timestamps in milliseconds hence absolute value of time, NOT dates). In order to treat letters like "hr" as literals you need to escape them. Example code:
// create timestamp
java.util.Date jud = new java.util.Date(260 * 1000); // milliseconds
// create format for timestamp
SimpleDateFormat sdf =
new SimpleDateFormat("yyyy'year',M'month',d'day',H'hr',m'min',s'sec'");
// otherwise you will get extra offset time (example: in England +1 hour DST)
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
// output: 1970year,1month,1day,0hr,4min,20sec
String formatted = sdf.format(jud);
System.out.println(formatted);
Even with the applied and tricky time zone correction in code you face the problem that you have an output for the year 1970, a point in time. Hereby you can see that SimpleDateFormat does format timestamps well (absolute values in time) but NOT durations (amount resp. length of time). This semantic problem can also not be solved by the approach to use java.util.Formatter as soon as the input increases the day limit of 86400 seconds.
Old JDK and Android don't offer a built-in solution for evaluating time differences expressed in years, months and days. Java 8 does offer (limited) support with new API (class 'Period' only for date part, not time part). External libraries like JodaTime or my own one (actually only as alpha-version) give more support. JodaTime even offers a special PeriodFormatter which is ideal for solving your problem.

Calculate Remaning Date Without Joda Time

I've spent an hour going through stackoverflow trying to find a proper way of calculating the remaining Days, hours, minutes and seconds remaining without using JODA-Time. I wish to keep things simple as possible.
I am seeking to do the following (Please provide declarations of instances, I am not sure as to whether to us Longs, Time or Calendar objects etc):
difference = endingDate-currentTime
Then set a textView to the time remaining with DD:HH:MM:SS format
In other words, what is the best method to use? (Timezone is not important) How can I set the ending date to for example December 31, 2013 and what type is my ending date? Is it a time, date or calendar object? I want to then subtract my current date from my ending date to display the remaining days left until December 31, 2013. In the format of DD:HH:MM:SS
Thank you! The help is much appreciated.
I'll leave you to work out how to divide the difference variable to get days, hours, etc. But this is how I'd do the rest of it.
Calendar endCalendar = new Calendar();
// Set end to 31th Dec 2013 10:15:30 am local time
endCalendar.set(2013, 11, 31, 10, 15, 30);
long localEndTimeInMillis = endCalendar.getTimeInMillis();
long localCurrentTimeInMillis = Calendar.getInstance().getTimeInMillis();
// Convert to UTC.
// Easy way to compensate if the current and end times are in different DST times
utcEndTimeInMillis = getUTCTimeInMillis(localEndTimeInMillis);
utcCurrentTimeInMillis = getUTCTimeInMillis(localCurrentTimeInMillis);
long difference = utcEndTimeInMillis - utcCurrentTimeInMillis;
The method to convert to UTC...
public long getUTCTimeInMillis(long localTimeInMillis) {
return localTimeInMillis - TimeZone.getDefault().getRawOffset() - (TimeZone.getDefault().inDaylightTime(new Date(localTimeInMillis)) ? TimeZone.getDefault().getDSTSavings() : 0);
}

Parcelable java.util.Date

I am trying to make one of my classes Parcelable, and one of its attributes is a Date object.
In the writeToParcel() method I have:
out.writeLong(myDate.getTime());
And in my createFromParcel() method I have
person.setDate(new Date(in.readLong() * 1000));
The Object that I am passing to my Intent has a Date created like this:
new Date(2000,12,06)
But, when I read it out on the other side, in the other activity:
myDate.getYear()+"-"+myDate.getMonth()+"-"+myDate.getDay()
It prints out "2001-0-0"
I'm assuming that something is getting screwed up during the parcel process?
You're writing out milliseconds since the Unix epoch (see the documentation for getTime()).
The Date constructor that takes a long value takes in milliseconds since the Unix epoch (see the documentation for that constructor).
You, instead, are passing, microseconds since the Unix epoch to the constructor. Just pass the readLong() value to the Date constructor, and see if that helps.
Your error is in the way you create the Date object, check the documentation for more information about it.
Parameters
year, 0 is 1900 (e.g 100 is 2000).
month of the year, 0 - 11 (e.g. June is 5).
day of the month, 1 - 31 (don't think it needs example).
as you can see, when you do this "new Date(2000,12,06)", you are not creating the
date you thought you were creating on the first place. Also please not that the method
was deprecated since API 1, so please don't use it, unless you are targeting API 1, that
i don't think anyone is doing it anymore.
Also, as CommonsWare told you, remove the 1000 at the end while reading.

GregorianCalendar and SQLite

I'm trying to setup a RPG that will keep track of a virtual time. After some reading GregorianCalendar seems to be the best way to do this but I have some questions and hoping someone with experience could give me some insight.
Here is what I'm trying to do. The game will start in the year 1675 and run for about 30 years. At that point the character will retire if they have survived that long. The character will be able to choose from actions I've preset for them through the coarse of the game. Some actions will be short and take a hour, others may take a week or a month. The real question comes from me using SQLite heavily. I want to save the current time as well as how long an action will take in my database. My first thought when setting this up was, if I want to start the game in Aug 15, 1675 to have my data base with 3 rows, set those fields to 8, 15, 1675. Then also have 2 more columns for the time. Pull these int via cursor and set them with something like
GregorianCalendar time = new GregorianCalendar();
time.set(year, month, date, hour, minute);
I figured I would pull how long an action takes in a similar fashion. Have an int X, and then a string to tell whether this time is in minutes, hours, days etc. Then either add this int to the int pulled from database to add to the calendar directly.
Q: If I add it directly to the calendar how would I pull int values from the calendar to store in database to load at a later time (when the player loads their game)?
Q: If I add it to the int stored in the database and set the calendar with this new int what will happen when I add enough to make the int out of scope for the calendar (Date is set to 31 but I add another day)?
You can convert from the GregorianCalendar object to/from UNIX time for example using getTimeInMillis() setTimeInMillis(). GregorianCalendar also has a roll() method:
Adds the specified amount to the specified field and wraps the value
of the field when it goes beyond the maximum or minimum value for the
current date. Other fields will be adjusted as required to maintain a
consistent date.
I would recommend using Joda Time as a substitute for the (somewhat lacking) standard java date and time utilities. It's much more flexible.
It has functions to do date math, it supports several different calendars (ISO8601, Buddhist, Coptic, Ethiopic, Gregorian, GregorianJulian, Islamic, Julian), has support for intervals, durations and periods. It has built in formatters that let you make your output look like just about anything you wish.
If it were me, I would use Joda and store the date in the native format presented by Joda (I don;t remember what that is right offhand) and then pull it out again and use Joda to do all the date math, as well as having it convert it to whatever calendar you wish to use for display to the user.
Otherwise, it seems to me you'd be re-inventing the wheel.

Using System.currentTimeMillis() to get time on emulator

I've being using System.currentTimeMillis() to get the current time of an action occuring in my Android activity. The time it gives when converted to a date something like this Thu 20 January 1970 20:15. I am wondering if this is just because I am using it on the emulator of is there something gone wrong?
EDIT:
times = System.currentTimeMillis();
//Converting to Date using constructor Date(long milliseconds)
Date changeToDate = new Date(times);
It's just a guess: you probably convert millis to date incorrectly. Don't you divide them by 1000 while passing to Date constructor?
which Date class did you import in your project? probably you have imported java.sql.Date but the one which you should use is java.util.Date - perhaps this helps a little bit.. #a.ch. : java.util.Date needs milliseconds, not seconds (ms/1000) in its constructor ;)

Categories

Resources