How to parse date without using Local Time Zone? - android

From Server I get following values:
epochMillis=1556532279322
iso8601=2019-04-29T10:04:39.322Z
When I do serverTimeDateFormat.parse(iso8601), I get as a result Mon Apr 29 10:04:39 GMT+02:00 2019
and for serverTimeDateFormat.parse(iso8601).time, the result is 1556525079322, which is different from what I get from the server (2 hours behind from UNIX time), while I am in timeZone + 2 hours.
When I format it back with serverTimeDatFormat.format(1556525079322), the result is 2019-04-29T10:04:39.322Z
I understand that SimpleDateFormat is using local timezone, but why is the result 2 hours behind and how can I parse the Date without taking into account timezone? I don't understand the logic of all this.
My code:
private val serverTimeDateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",Locale.ENGLISH)
val iso8601 = "2019-04-29T10:04:39.322Z"
val epochMillis = 1556532279322
serverTimeDateFormat.parse(iso8601).time

The problem lies with the pattern for your SimpleDateFormat. At the end, you have 'Z', which indicates there should be a literal "Z" in the date string to be parsed. However, the "Z" at the end of the date has a special meaning, namely it signifies the UTC timezone. Hence, you should parse it as a timezone designator so that the correct date value will be obtained. You can do this with the pattern XXX (See JavaDocs).
private val serverTimeDateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX",Locale.ENGLISH)
val iso8601 = "2019-04-29T10:04:39.322Z"
print( serverTimeDateFormat.parse(iso8601).time ) // 1556532279322
Runnable example on pl.kotl.in
Addendum: While the above code should work for you, if at all possible, you should consider adding ThreeTen Android Backport to your project. This will give you access to the newer time classes added by JSR310 to Java/Kotlin (Also available by default in Android API >=26). The classes have generally easier API, and use ISO8601 by default, so you wouldn't need any formatter at all:
print( ZonedDateTime.parse(iso8601).toInstant().toEpochMilli() )

Avoid legacy date-time classes
You are using terrible date-time classes that were supplanted years ago by the modern java.time classes defined in JSR 310.
Date::toString lies
why is the result 2 hours behind
It is not actually two hours behind.
The problem is that while a java.util.Date represents a moment in UTC, its toString method dynamically applies the JVM’s current default time zone while generating the text representing the value of the date-time object. While well-intentioned, this anti-feature confusingly creates the illusion of the Date object having that time zone.
In other words, Date::toString lies. One of many poor design decisions found in these legacy classes. And one of many reasons to never use these legacy classes.
java.time
Instant
Parse your count of milliseconds since the epoch reference of first moment of 1970 in UTC as a Instant.
Instant instant = Instant.ofEpochMilli( 1556532279322 );
Your other input, a standard ISO 8601 string, can also be parsed as an instant.
Instant instant = Instant.parse( "2019-04-29T10:04:39.322Z" ) ;
ZonedDateTime
To see the same moment through the wall-clock time used by the people of a particular region (a time zone), apply a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ) ;
Both the instant and zdt objects represent the same simultaneous moment. Two ways of reading the same moment, as two people conversing on the phone in Iceland and Québec would each see a different time on the clock on the wall while glancing simultaneously.

Related

How to get current date with reset time 00:00 in kotlin

Hey I am using calendar instance to get current date and time.
private fun getCurrentCalendar() { Calendar.getInstance() }
Output:- Wed Jul 20 21:45:52 GMT+01:00 2022
If I want to reset time I need to use this function
fun resetCalendarTime(calendar: Calendar) {
calendar.set(Calendar.HOUR_OF_DAY, 0)
calendar.set(Calendar.MINUTE, 0)
calendar.set(Calendar.SECOND, 0)
calendar.set(Calendar.MILLISECOND, 0)
}
it will give this
Wed Jul 20 00:00:00 GMT+01:00 2022
My question is there any efficient way of doing that or this is fine in android?
Caveat: Java syntax shown here, as I have not yet learned Kotlin.
tl;dr
LocalDate.now( zoneId ).atStartOfDay( zoneId )
Details
The terrible java.util.Calendar class was years ago supplanted by the modern java.time classes defined in JSR 310. Never use either Date class, Calendar, SimpleDateFormat, or any other legacy date-time class found outside the java.time package.
On JVM
If you are running Kotlin on a JVM, use java.time classes.
To get the current moment as seen in a particular time zone, use ZonedDateTime.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
If you want to use the JVM’s current default time zone:
ZoneId z = ZoneId.systemDefault() ;
Apparently you want the first moment of the day. Your Question makes the mistake of assuming that time is always 00:00. Actually, on some dates in some time zones, the first moment occurs at a different time such as 01:00.
👉 So let java.time determine the first moment of the day. Call LocalDate#atStartOfDay.
A LocalDate represents a date-only value, without time-of-day, and without time zone or offset. Calling atStartOfDay returns a ZonedDateTime, like that seen above.
LocalDate today = LocalDate.now( z ) ;
ZonedDateTime startOfToday = today.atStartOfDay( z ) ;
Here is an example of a day starting at 1 AM.
ZoneId z = ZoneId.of( "Asia/Amman" ) ;
LocalDate ld = LocalDate.of( 2021 , 3 , 26 ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
See this code run live at Ideone.com. Notice the time is 01:00.
2021-03-26T01:00+03:00[Asia/Amman]
To generate text in standard ISO 8601 format wisely extended to append the name of the time zone in square brackets, merely call ZonedDateTime#toString. See example result quoted directly above this paragraph.
To generate text in other formats, use DateTimeFormatter, and optionally DateTimeFormatterBuilder. To automatically localize, use DateTimeFormatter#ofLocalizedDateTime.
All of this has been covered many many times on Stack Overflow. Search to learn more.
Off JVM
I recall that some part of the Kotlin community was working on a Kotlin-based port of a subset of java.time functionality to be used for Kotlin-based apps not running on a JVM.
I imagine that ported library works similar to code shown above.

How can I select records from a table where unixtime(integer) column contains the current date without considering the time?

I'm having a table with the following fields in Android SQLite database.
In this, due_date column is INTEGER, i just want the records which matches today's date(current date) alone in due_date without considering time.
For example: If I have 3 values matching with current date, I need to return all 3 rows
Note: In my case, have to compare with current date not with current
timestamp but my column type was INTEGER having unix-epoch value.
My unix-epoch example is "1526565900000".
I have tried:
date('now', 'start of day') // not working
date('now','localtime','start of day') // not working
select strftime('%d', date('now')), name, due_date from task group by due_date;
this too not working for my requirement.
Finally as per the comments below i changed all my datetime and
timestamp column into INTEGER to store as unix-epoch value before that all my column were in timestamp.
Step 1: First i changed the column type to int as #CL mentioned where it was declared as datetime and timestamp before.
Step 2: Then inserted all the datetime values in seconds(which is 10 digit) as #pskink said in comments.
Step 3: To get start and end value of current date in seconds i used the following java code.
//getCurrentDateTimeInMilliseconds
public void getCurrentDateTimeInMilliseconds() {
Date todayStart = new Date();
Date todayEnd = new Date();
todayStart.setHours(0);
todayStart.setMinutes(0);
todayStart.setSeconds(0);
todayEnd.setHours(23);
todayEnd.setMinutes(59);
todayEnd.setSeconds(59);
long endTime = todayEnd.getTime();
}
using this you can get the start and end value of current day like this
todayStart.getTime()
it will return value in milliseconds which is 13 digit value to convert this to seconds just divide by 1000 like this,
long startDateInSeconds = todayStart.getTime/1000;
long startDateInSeconds = todayEnd.getTime/1000;
and use these values in the sqlite query based on requirement in my case the query will be as follows:
String query = "select * from task where due_date>" + startDateInSeconds + " and due_date<" + startDateInSeconds;
and then pass the query in the method of databasehelper class like this,
Cursor cursor = databasehelper.getData(query);
in DatabaseHelper.java(which should extends SQLiteOpenHelper class) file do the following code:
public Cursor getData(String query) {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
return sqLiteDatabase.rawQuery(query, null);
}
finally nailed it with the help of #pskink, thanks for your comments helped me a lot.
Data stored like this in my db.
tl;dr
myPreparedStatement.setObject( // Generally best to use Prepared Statement, to avoid SQL Injection risk.
1 , // Specify which placeholder `?` in your SQL statement.
LocalDate.now( ZoneId.of( "Pacific/Auckland" ) ) // Determine today’s date as seen in the wall-clock time used by the people of a certain continent/region (a time zone).
.atStartOfDay( ZoneId.of( "Pacific/Auckland" ) ) // Determine the first moment of the day on that date in that zone. Not always 00:00:00.
.toInstant() // Adjust that first moment of the day in that zone to the wall-clock-time of UTC.
.getEpochSecond() // Get a count of whole seconds since the epoch reference of 1970-01-01T00:00:00Z.
)
java.time
The modern approach uses the java.time classes that supplanted the troublesome old legacy date-time classes.
In this, due_date column is INTEGER, i just want the records which matches today's date(current date) alone in due_date without considering time.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Epoch seconds
We need to translate that date to a number, the count of seconds since the epoch reference of first moment of 1970 in UTC.
To do that, we need to get the first moment of the day. Let java.time determine that first moment. Do not assume the day starts at 00:00:00. Anomalies such as Daylight Saving Time (DST) mean the day may start at another time such as 01:00:00. Specify a time zone to get a ZonedDateTime object.
ZonedDateTime zdt = today.atStartOfDay( z ) ;
We must adjust into UTC from our zone. Easiest way to do this is to extract an Instant. The Instant class is always in UTC by default.
Instant instant = zdt.toInstant() ; // Adjust from our zone to UTC.
Get the number of seconds since epoch.
long secondsSinceEpoch = instant.getEpochSecond() ;
As a shortcut, we could have asked for seconds-from-epoch directly from the ZonedDateTime class. But I wanted to make clear that we are working adjusting from a particular time zone to UTC.
long startSecondsSinceEpoch = zdt.toEpochSecond() ; // Shortcut for adjusting from time zone to UTC, and then getting count of seconds since epoch.
We also need the ending of our time range, to find all records whose date is today’s date. We will use the first moment of the following day. This follows the usual practice of Half-Open definition of a span of time. In Half-Open, the beginning is inclusive while the ending is exclusive.
long stopSecondsSinceEpoch = ld.plusDays( 1 ).atStartOfDay( z ).toEpochSecond() ;
SQL
Now we are ready for the SQL statement. Generally best to make a habit of using a prepared statement.
String sql = "SELECT when FROM tbl WHERE when >= ? AND when < ? ; " ;
…
myPreparedStatement.setObject( 1 , startSecondsSinceEpoch ) ;
myPreparedStatement.setObject( 2 , stopSecondsSinceEpoch ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
SELECT * FROM your table name where due_date BETWEEN date('now') AND strftime('%Y-%m-%d', due_date)

Convert Java.util.Calendar to org.threeten.bp.LocalDateTime (for Android)

How to convert from Android Java Date and Calendar to threeten LocalDateTime
Calendar calTime = Calendar.getInstance();
Date date = calTime.getTime();
LocalDateTime ldt = Instant.ofEpochSecond(date.getTime()/1000)
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
Fixed!
Your solution is less than optimal.
LocalDateTime has no zone/offset
Firstly, your use of LocalDateTime is inappropriate almost certainly. You are discarding valuable information about time zone or offset. The LocalDateTime class purposely has no concept of time zone or offset-from-UTC, and therefore does not represent an actual moment, only a rough idea about possible moments over a range of 26-27 hours or so.
Instead use Instant, OffsetDateTime, and ZonedDateTime when dealing with actual moments on the timeline.
We only use LocalDateTime when:
We do not know the zone.
We intend multiple zones for a non-simultaneous moment (“all our factories around the world close at noon for lunch”).
We are scheduling out into the future more that a few weeks and so we get might get hit by capricious politicians re-defining the time zone such as Daylight Saving Time (DST) with little notice. We use LocalDateTime for logic, and present to the user as a ZonedDateTime when generating a transient calendar.
DateTimeUtils for conversions
Next, your conversion math is needless.
The DateTimeUtils class provides utility methods for conversions.
ZonedDateTime zdt = DateTimeUtils.toZonedDateTime( myCalendar ) ;
or…
Instant instant = DateTimeUtils.toInstant( myCalendar ) ;
P.S. Do not answer your Question inside the body text of the Question. Instead, post an actual Answer, and then accept it to close the Question.
Tips: For those wanting to use ThreeTen-Backport in Android, see the ThreeTenABP project. And see How to use ThreeTenABP in Android Project.

SimpleDateFormat.parse() ignoring timezone?

I am trying to parse date string with timezone using this code for tests:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZZZZZ", Locale.US);
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse("2017-07-26T06:00-06:00"));
int offset = calendar.getTimeZone().getRawOffset();
I am trying to change timezone from -06 to +09, but offset always contains 10800000.
How to parse date with timezone correctly (I need time and timezone both)?
Note: -06:00 is an offset, not a timezone - those 2 concepts are related, but they are different things (more on that below).
The problem with SimpleDateFormat and Calendar is that they use the system's default timezone, so even though you parse a date with a different offset (like -06:00), the resulting Calendar will have the default timezone (you can check what zone is by calling TimeZone.getDefault()).
That's just one of the many problems and design issues of this old API.
Fortunately, there's a better alternative, if you don't mind adding a dependency to your project (in this case, I think it's totally worth it). In Android you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, you'll also need the ThreeTenABP to make it work (more on how to use it here).
To work with offsets, you can use the org.threeten.bp.OffsetDateTime class:
// parse the String
OffsetDateTime odt = OffsetDateTime.parse("2017-07-26T06:00-06:00");
This will parse all the fields correctly (date/time and offset). To get the offset value, similar to calendar.getTimeZone().getRawOffset(), you can do:
// get offset in milliseconds
int totalSeconds = odt.getOffset().getTotalSeconds() * 1000;
I had to multiply by 1000 because calendar returns the value in milliseconds, but ZoneOffset returns in seconds.
To convert this to another offset (+09:00), it's straightforward:
// convert to +09:00 offset
OffsetDateTime other = odt.withOffsetSameInstant(ZoneOffset.ofHours(9));
As I said, timezone and offset are different things:
offset is the difference from UTC: -06:00 means "6 hours behind UTC" and +09:00 means "9 hours ahead UTC"
timezone is a set of all the different offsets that a region had, has and will have during its history (and also when those changes occur). The most common cases are Daylight Saving Time shifts, when clocks change 1 hour back or forward in a certain region. All these rules about when to change (and what's the offset before and after the change) are encapsulated by the timezone concept.
So, the code above works fine if you're working with offsets and wants to convert to a different one. But if you want to work with a timezone, you must convert the OffsetDateTime to a ZonedDateTime:
// convert to a timezone
ZonedDateTime zdt = odt.atZoneSameInstant(ZoneId.of("Asia/Tokyo"));
// get the offset
totalSeconds = zdt.getOffset().getTotalSeconds() * 1000;
The getOffset() method above will check the history of the specified timezone and get the offset that was active in that corresponding instant (so, if you take a date during DST, for example, the offset (and also date and time) will be adjusted accordingly).
The API uses IANA timezones names (always in the format Region/City, like America/Sao_Paulo or Europe/Berlin).
Avoid using the 3-letter abbreviations (like CST or PST) because they are ambiguous and not standard.
You can get a list of available timezones (and choose the one that fits best your system) by calling ZoneId.getAvailableZoneIds().
You can also use the system's default timezone with ZoneId.systemDefault(), but this can be changed without notice, even at runtime, so it's better to explicity use a specific one.

Convert milliSeconds To Gregorian Calendar

I want to convert milliSeconds in long format to Gregorian Calendar.
By searching in the web, i use the code below:
public static String getStringDate(int julianDate){
GregorianCalendar gCal = new GregorianCalendar();
Time gTime = new Time();
gTime.setJulianDay(julianDate);
gCal.setTimeInMillis(gTime.toMillis(false));
String gString = Utils.getdf().format(gCal.getTime());
return gString;
}
public static SimpleDateFormat getdf(){
return new SimpleDateFormat("yyyy-MM-dd, HH:MM",Locale.US);
}
Yes, the code works but i find that only the date and the hour are correct but there are errors on minutes. Say if the thing happens on 2014-11-06, 14:00, it will give me 2014-11-06, 14:11. I want to know are there any solutions to modify it or it is not recommended to convert time into Gregorian Calendar. Many thanks!
The problem actually is very simple,
modify SimpleDateFormat("yyyy-MM-dd, HH:MM",Locale.US) with
SimpleDateFormat("yyyy-MM-dd, HH:mm",Locale.getDefault());
will solve the problem
tl;dr
Instant.ofEpochMilli( millis ) // Convert count-from-epoch into a `Instant` object for a moment in UTC.
.atZone( ZoneId.of( "Pacific/Auckland" ) ) // Adjust from UTC to a particular time zone. Same moment, different wall-clock time. Renders a `ZonedDateTime` object.
.format( // Generate a String in a particular format to represent the value of our `ZonedDateTime` object.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd, HH:mm" )
)
java.time
The modern approach uses the java.time classes instead of those troublesome legacy classes.
Convert your count of milliseconds since the epoch reference of first moment of 1970 (1970-01-01T00:00Z) to a Instant object. Be aware that Instant is capable of finer granularity of nanoseconds.
Instant instant = Instant.ofEpochMilli( millis ) ;
That moment is in UTC. To adjust into another time zone, apply a ZoneId to get a ZonedDateTime.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Generate a string in your desired format using a DateTimeFormatter object.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd, HH:mm" , Locale.US ) ;
String output = zdt.format( f ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

Categories

Resources