so, let's say I want to save a data in my database and save the timestamp (date and time) for the time the data saved in database. for example in +3:00 GMT.
now the timezone changed and the saved time when I getting it is changing too but I don't want that.
I want it to show the time in that timezone not current
and I using currentTimeMillis() for getting time
it's my code of getting time
val timeStamp = System.currentTimeMillis()
and code for getting from database in my view holder
val tsLong = currentItem.timeStamp
System.currentTimeMillis will always report in UTC regardless of the user's timezone.
I would recommend using Instant to store all your timestamps. Instants can easily be converted to any timezone. Instant has the following advantages:
Explicitly always in UTC/GMT timezone
toString() to ISO date format that is much more readable than milliseconds from the epoch
Far too often when we use milliseconds from the epoch we can't easily read them and it's ambitious if the field is seconds from the epoch or milliseconds. using Instant removes this ambiguity and makes things easier for developers.
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.
I want to get the current date as yyyy-MM-dd from SQLite, I use the following query:
***SELECT date('now')***
But instead of returning the current date, it returns the next day from today.
For example, today (2015-12-01) I run the query and it returns (2015-12-02).
What I did wrong?
Image running query + calendar
sqlite date and time functions use UTC time zone internally. In UTC the date was already 2015-12-02.
If you want to use another timezone, you need to specify it explicitly, e.g.
select date('now','-05:00');
I'd suggest to use UTC millisecond timestamps in your database layer though and have the presentation logic such as date formatting with timezone adjustment in your app code.
Reference: https://www.sqlite.org/lang_datefunc.html
I am using (maybe incorrectly) a Joda DateTime to store a reminder time in a reminders app. When the timezone changes on the device (because of DST or just moving to a different TZ) I want to be able to reset the reminders to use the current timezone but keep the time.
For example: I set a reminder for Friday May 15th, at 15:00. If the timezone changes before that time, I want to be able to recreate the reminder for Friday May 15th at 15:00 local time.
I have already tried to use withZoneRetainFields but I haven't been able to keep the time unchanged:
new DateTime(reminderTimeMillis, DateTimeZone.forID(previousTimeZone)).withZoneRetainFields(DateTimeZone.getDefault())
Well, that method should basically work:
#Test
public void change_timezone_of_reminder() {
DateTime originalReminderDateTime = LocalDateTime.parse("2015-05-15T15:00").toDateTime(
DateTimeZone.forID("Europe/Berlin"));
assertThat(originalReminderDateTime.toString(), equalTo("2015-05-15T15:00:00.000+02:00"));
long reminderMillis = originalReminderDateTime.getMillis();
DateTime updatedTime = new DateTime(reminderMillis, DateTimeZone.forID("Europe/Berlin"))
.withZoneRetainFields(DateTimeZone.forID("America/New_York"));
assertThat(updatedTime.toLocalDateTime(), equalTo(LocalDateTime.parse("2015-05-15T15:00")));
assertThat(updatedTime.toString(), equalTo("2015-05-15T15:00:00.000-04:00"));
}
So, how are you evaluating that the time field is not changing?
Also, if you are storing the reminder time as millis-after-epoch, you don't need to adjust it for DST shifts, if you're calculating the millis using a full timezone ("Europe/Berlin") rather than a fixed offset.
..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();