I want to subtract two dates in Android project.
When I use the statement:
DateTime now = new DateTime(DateTimeZone.UTC);
It gives 2014-03-17T12:49:06.670Z value instead of 2014-03-17T14:49:06.670Z (this is my current time on Android device)
When I convert this DateTime (2014-03-17T12:30:08.673+02:00) to UTC Time (2014-03-17T10:30:08.673Z) it gives the correct result but not for DateTime now = new DateTime(DateTimeZone.UTC);
What is wrong with new DateTime(DateTimeZone.UTC);?
Any help would be appreciated.
Try getting your local time this way:
DateTime now = new DateTime();
This time is "your current time on Android device". More precisely DateTime calculates its fields with respect to a time zone. It means it will return UTC+2 if you are located in Eastern European Countries (Winter Time) or Wester European Countries (Summer time).
On my PC nothing is wrong with new DateTime(DateTimeZone.UTC). The type DateTime internally stores the given time zone (here UTC) and uses it for the output of its method toString(), hence the UTC-string-format and not another alternative format with offset = +02:00.
Related
I am trying to fill 2 date objects, one in Local time and the other in UTC.
I AM NOT TRYING TO PRINT THE DATE AS A STRING IN GMT/UTC, please do not suggest DateFormatting, and dont say its a duplicate until you read the full question.
Local, I have no problem:
Date dateLocal = new Date();
The problem is I cant get the utcDate to be UTC.
Using a Calendar like so:
TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
Calendar c = new GregorianCalendar();
c.setTime(new Date());
c.setTimeZone(TimeZone.getTimeZone(utcTimeZone.getID()));
Date utcDate = c.getTime();
When debugged or submitted to the webservice, utcDate shows in my local timezone, instead of UTC.
Using Joda:
DateTime utcDateTime = DateTime.now(DateTimeZone.UTC);
Date utcDate = utcDateTime.toDate();
Same issue, utcDate when debugged/submitted to webservice is showing in local time.
Here is how the object looks when debugged:
This is an issue because this causes the webservice (which i have no access to) to think this time is UTC, so when it does its work and conversions, the time is always off by 4 hours, since for me the UTC to Local conversion is GMT -4.
The ONLY way i have been able to get this to submit the date in UTC time is by adding:
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
BUT this also changes the LocalTime object, even though this object was defined and set before the default TimeZone was changed.
So i get it, the Date() object uses the JVM locale, so any time a Date is created, its created in the default timezone, and apparently whenever the default timezone is changed, all of the Date objects (even if they are already created) change to the new default timezone... I know Date objects are just the millis between now and 1970 whatever, but the TimeZone is obviously being taken into account in the Webservice and this is messing up my results...how can i get the dates the way i want?
So time formatting and adjusting has always been my biggest nemesis in programing and I'm having some issues in Android/Java that I can't figure out. I get a timestamp from a server that is formatted in UTC (here's an example 2016-06-17T18:30:00-07:00. Now this time needs to get formatted to the users local time (so for a user in PST it should show as 11:30AM) but so far whatever I try I either get 1AM or 6:30PM (so I know I'm doing something wrong I just don't know what). Here's what I've been trying to do
public static DateTime convertISOStringToDate(String inputString) {
//setup the ISO Date Formatter with GMT/UTC format
DateTimeFormatter formatter = ISODateTimeFormat.dateTimeParser()
.withLocale(Locale.US)
.withZone(DateTimeZone.forOffsetHours(0));
DateTime dateTime = formatter.parseDateTime(inputString);
//now convert the datetime object to a local date time object
DateTimeFormatter localFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
.withZone(DateTimeZone.getDefault());
String localString = localFormatter.print(dateTime);
DateTime localDateTime = localFormatter.parseDateTime(localString);
return localDateTime;
So at this point I'm getting 1:30AM, so I know I'm messing it up somewhere in the conversion process but I can't figure it out. I've been trying to google around but so far haven't found much that use the ISODateTimeFormat parser so they don't work either when I try them.
You seem to have a basic mis-understanding of how dates are represented.
A date (in almost every known programming language / library) is represented internally as an offset from a specific 'origin time', known as the 'Epoch'.
In java.util.Date as well as joda dates, the internal representation is the number of milliseconds since midnight, Jan 1, 1980, UTC.
As such, a date does not have a timezone. You only introduce a timezone when you format a date (turn it into a String representation of the date).
You have made the common mistake of parsing a String into a date object, serializing (printing) it back out with a different timezone than the the original string indicated, and then parsing back into a date again, expecting something to have changed. If you do that correctly, you will get back exactly the same date that you started with.
In your case, the "localString" that you get shows the correct time in the local timezone. I'm in EDT, which is UTC-4:00, and I correctly get 2016-06-17 21:30:00 as the result.
As I said, parsing that back into a DateTime, and then looking at it is useless, because:
You'll get the same DateTime back that you started with
Your IDE (or whatever you're using to inspect the DateTime) probably isn't showing what you expect.
You should re-evaluate what you're doing here, and whether you really need to "convert" the DateTime, or to just parse it, and really understand how date formatting works with respect to timezones.
..and later retrieve and show them as Strings?
I'm asking the user some input and I want to store both the date (i.e., day, month and year) and the time (i.e., the hour of the day) this input was submitted. Each submission is then saved in my SQlite database, and later retrieved from a RecyclerView.
I'm facing two problems at least. Right now I set up two TEXT fields in the database, FIELD_DATE and FIELD_TIME, where I'd like to store the string representation of date & time, in a format depending on the Android user locale.
From what I've read, the android.text.format.DateFormat should help me. So I set:
java.text.DateFormat dateFormat = DateFormat.getMediumDateFormat(getActivity());
java.text.DateFormat timeFormat = DateFormat.getTimeFormat(getActivity());
Now I think I should call format(Date d) on both objects to get my string, but I don't know where do I get this Date object - don't even know if my two lines are correct. So:
How to get a string representation of current date & time, based on the user defined (at OS level) locale?
That said (asked), I wonder if two fields for date & time are really what I'm looking for. As said, at the end I would like to show a RecyclerView reading the database. In that I will also need to filter out entries based on date, i.e.
Entries referring to last week // last month // All
entries
So I'm also asking:
Is a two-text-fields pattern the right choice to store date & time, given the need to easily filter out entries belonging to, say, last week? Should I better have separate columns for day, month and year?
How to query the database to have only last week rows, given the FIELD_DATE / FIELD_TIME structure (or any other better structure you can suggest)?
I'm quite stuck on these three questions.
Edit: finally came up with how to get the strings I wanted at first, it was as simple as instantiating a new Date object:
Date d = new Date();
String date = DateFormat.getMediumDateFormat(getActivity()).format(d);
String time = DateFormat.getTimeFormat(getActivity()).format(d);
Now I have both the needs to display these strings (which is quite simple, as they are already formatted) and to apply some filter to the db, like entries belonging to last week (which, in turn, would be quite simple with current time in millis since 1970). What to do?
If you want to be able to run complex queries such as find all records from last week, I would recommend storing a timestamp in an integer instead. A timestamp is expressed as the number of milliseconds since the Epoch (Jan 1, 1970). It makes it easy to make queries on exact date and time ranges.
The timestamp is easily found from e.g. System.currentTimeMillis().
The other approach would be to use sqlite's built in date type, but I would personally choose the timestamp approach.
Is there any reason you would want to store it in the current locale's format in the first place? If you are displaying the date to the user you're likely better of formatting the timestamp into a date when displayed, using one of the many date features of Java and android such as java.util.Calendar, java.util.Date, android.text.SimpleDateFormat etc.
As an example, you could run this code to get the timestamp of the start of this month:
Calendar now = Calendar.getInstance();
now.set(Calendar.DAY_OF_MONTH, 1);
now.set(Calendar.HOUR_OF_DAY, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
long startOfThisMonth = now.getTimeInMillis();
What I need is a time difference between specific timezone ("Russia/Moscow") and local time of the user, difference should be in hours.
I run into problem that the Difference of Time Zones is sometimes false calculated. I calculate difference (in hours) between local offset to UTC of android device and remote offset to UTC. For most user it is fine.. but many user are complaining about the problem.. I am not able to reproduce it at my phone or emulators.
The "wrong" displayed time difference is all ways 1 hour less.
In Moscow it is 15:00, in Europe 12:00. But the user see the offset of 2 hours
here is my code.
String tz="Europe/Moscow"
Calendar mCalendar = new GregorianCalendar();
mCalendar.setTimeZone( TimeZone.getTimeZone(tz));
TimeZone mTimeZone = mCalendar.getTimeZone();
int remote = mTimeZone.getRawOffset()/1000/60/60;
Calendar mCalendar2 = new GregorianCalendar();
TimeZone mTimeZone2 = mCalendar2.getTimeZone();
int local = mTimeZone2.getRawOffset()/1000/60/60;
return local - remote;
You are making the common mistake of equating a Time Zone with a Time Zone Offset. They are two different things. Please read the timezone tag wiki.
When you call getRawOffset, that returns the standard offset for that time zone. To get the offset that's in effect at a particular point in time, you can use getOffset, which takes a parameter of the timestamp for the point in time you are talking about.
Consider the following code, which returns the difference that is currently in effect:
long now = System.currentTimeMillis();
String tz = "Europe/Moscow";
TimeZone mTimeZone = TimeZone.getTimeZone(tz);
int remote = mTimeZone.getOffset(now);
TimeZone mTimeZone2 = TimeZone.getDefault();
int local = mTimeZone2.getOffset(now);
double differenceInHours = (local - remote) / 3600000.0;
return differenceInHours;
Note a couple of things:
I did not need a Calendar class.
The offsets are both for the same "now". You will get different results depending on when you run it.
Not all offsets use a whole number of hours, so this function should return double, not int. For example, try Asia/Kolkata, which uses UTC+5:30 the whole year, or Australia/Adelaide, which alternates between UTC+9:30 and UTC+10:30.
Consider also using Joda-Time, which is a much more robust way of working with time in Java.
I create a GPS tracking, but when I use DDMS to send coordinate to the emulator and I want to get time of this coordinate through
Date date = new Date(gpsPos.getTime_stamp()); //gpsPos is an obj
gpsPos.setDate_time(date.toString());
The time I got from the function in miliseconds and I converted it to date using date class in java, but the date I got from converted is different from the real date of device.
How can i get the time location equals real time ? any idea? thx
what is the different between date.toString() and date.toGMTString()?
EDIT:
how can we solve it i want my gps time is equal to the real time (logic enough) in order to use it test sth later?
Date(milliSeconds) will create the Date object based on GMT, Date.toString will create a string based on your locale (by default but can be modified). If the milliseconds you used to create the Date object is actually based on your Locale then your time will be off by 4 hours if you're in EDT as an example.