Hey I have Iso Format date. I want to compare with current date. If date is equal to current date, I need the time of given Iso date and otherwise i need date.
val date = "2021-10-01T18:39:10.0492422+01:00"
How to compare today’s date with this value. If date is match i need time in HH:MM otherwise dd MMM YYYY format.
Important thing my minSdkVersion 21
tl;dr
Java syntax, as I don’t know Kotlin:
LocalDate
.now( ZoneId.of( "America/Edmonton" ) )
.isEqual(
OffsetDateTime
.parse( "2021-10-01T18:39:10.0492422+01:00" )
.atZoneSameInstant( ZoneId.of( "America/Edmonton" ) )
.toLocalDate()
)
As for generating text from java.time objects in specific formats using DateTimeFormatter and DateTimeFormatterBuilder classes, that has been covered many many times already. Search to learn more.
Details
The latest Android tooling brings much of the java.time functionality built into Android 26+ to earlier Android via “API de-sugaring”.
In Java syntax…
Parse your input as a OffsetDateTime.
OffsetDateTime odt = OffsetDateTime.parse( "2021-10-01T18:39:10.0492422+01:00" ) ;
Adjust to the time zone by which you perceive “today’s date”.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
Get today’s date as seen in your target time zone, a LocalDate.
LocalDate today = LocalDate.now( z ) ;
Compare to the date of our input as seen in the same time zone.
boolean sameDate = today.isEqual( zdt.toLocalDate() ) ;
As seen above, you must provide a time zone. For any given moment, the date varies around the globe by time zone. Right now is “tomorrow” in Tokyo Japan while simultaneously “yesterday” in Toledo Ohio US. So to ask “what is the date today?”, you must also specify where, that is, by what time zone do you want to perceive the current date.
Related
Hello I am trying to Start of Day
Like in India TimeZone
Start of Day is: 2022-11-20 00:00:00 (local time in India)
In UTC: 2022-11-20 05:30:00 PM
tl;dr
LocalDate // Represent a date-only value, without time-of-day, without time zone or offset.
.now( ZoneId.of( "Asia/Kolkata" ) ) // Capture the current date as seen in a particular time zone. For any given moment, the date varies around the globe by time zone.
.atStartOfDay( ZoneId.of( "Asia/Kolkata" ) ) // Determine the first moment of the day. May or may not be 00:00. Returns a `ZonedDateTime` object.
.toInstant() // Adjust to an offset from UTC of zero hours-minutes-seconds. Returns an `Instant` object.
.toString() // Generate text in standard ISO 8601 format. Returns a `String` object, containing formatted text.
2022-11-19T18:30:00Z
Details
Capture the current date.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
LocalDate today = LocalDate.now( z ) ;
Get the first moment of that day. Do not assume the day starts at 00:00. Some days on some dates in some time zones start at a different time of day such as 01:00. Let java.time determine the first moment.
ZonedDateTime zdt = today.atStartOfDay( z ) ;
To view that same moment through the wall-clock time of UTC (an offset from UTC of zero hours-minutes-seconds), extract an Instant. An Instant represents a moment, a specific point on the timeline, as seen in UTC.
Instant instant = zdt.toInstant() ;
See that code run at Ideone.com.
today.toString(): 2022-11-20
zdt.toString(): 2022-11-20T00:00+05:30[Asia/Kolkata]
instant.toString(): 2022-11-19T18:30:00Z
To generate text in various formats, use OffsetDateTime rather than Instant. The Instant class is a basic building-block class in java.time. The OffsetDateTime class is more flexible, including features for generating text in formats other than standard ISO 8601 format.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
To learn more about generating text, search Stack Overflow for existing Questions and Answers about DateTimeFormatter class.
Java 8+ comes with an implementation of java.time. Ditto for Android 26+. For earlier Android, the latest tooling provides most of the java.time functionality via “API desugaring”.
I need to create a class that implements JsonbDeserializer < ZonedDateTime > , but, the data (string) to be parsed could be in this format "2021-05-31" or this format "2021-05-31T09:30:57.544797".
How could I deal with this scenario?
Neither of your pieces of example data are suitable for a ZonedDateTime object.
Date without time, and without zone
"2021-05-31" represents a date-only value. Use LocalDate class.
LocalDate ld = LocalDate.parse( "2021-05-31" ) ;
If you want to make a ZonedDateTime of that, you’ll to assign a time-of-day and a time zone.
Perhaps you’d want the first moment of the day as the time. If so, do not assume that first moment is at 00:00:00. Some dates in some zones start at a different moment such as 01:00:00. Let java.time determine the first moment.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
Date and time without zone
"2021-05-31T09:30:57.544797" represents a date with a time of day, but lacks an indicator of time zone or offset from UTC. So parse as a LocalDateTime.
LocalDateTime ldt = LocalDateTime.parse( "2021-05-31T09:30:57.544797" ) ;
If you want to make a ZonedDateTime of that, assign a time zone. Be aware the time of day may change to adjust for gaps caused by anomalies such as Daylight Saving Time (DST).
ZoneId z = ZoneId.of( "Asia/Japan" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
I'm tring to convert this date string "2021-12-10T00:00:00" into a Date but when i deserialize it i got this.
Thu Dec 09 19:00:00 COT 2021.
it seems I'm losing one day.
Can anyone help me?
"startDate": "2021-12-10T00:00:00", and the result is this
2021-12-09T19:00:00.000-0500
tl;dr
java.util.Date.from(
LocalDateTime
.parse( "2021-12-10T00:00:00" )
.atZone(
ZoneId.of( "America/Bogota" )
)
.toInstant()
)
Details
I am guessing that you are using the terrible legacy date-time classes such as Date and Calendar. Don’t. Use only java.time class.
Your input string complies with the ISO 8601 standard for date-time formats. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
LocalDateTime ldt = LocalDateTime.parse( "2021-12-10T00:00:00" ) ;
You said:
I'm tring to convert this date string "2021-12-10T00:00:00" into a Date
That does not make sense.
I assume by “Date”, you meant a java.until.Date. That legacy class represents a moment, a point on the timeline as seen in UTC, that is, with an offset from UTC of zero hours-minutes-seconds.
But your input lacks an indicator of time zone or offset. For example, if that string was meant to represent a moment as seen in UTC, it should have had a Z appended.
I am guessing that you assume the input was meant to represent a moment as seen in Colombia.
ZoneId z = ZoneId.of( "America/Bogota" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
Now we have determined a moment as seen through the wall-clock time used by the people of Colombia.
Generally best to avoid java.util.Date class. But if you must, to interoperate with legacy code not yet updated to java.time, you can convert.
java.util.Date d = Date.from( zdt.toInstant() ) ;
Your start date is 2021-12-10 00:00:00 GMT+0 and your result is 2021-12-09 19:00:00 GMT-5. These times are the same. You can pass a Locale to your SimpleDataFormat constructor to be able to configure the used time zone.
This question already has answers here:
Change date format in a Java string
(22 answers)
Closed 4 years ago.
I want to display complete date in mySQL format but don't want to see the Time along with it.
Wanted to increment or decrement the date to perform actions
tl;dr
myResultSet.getObject( … , Instant.class )
.atZone( ZoneId.of( "Pacific/Auckland" ) )
.toLocalDate()
.toString()
Details
For a column of type akin to the SQL-standard TIMESTAMP WITH TIME ZONE, retrieve as a Instant.
Instant instant = myResultSet.getObject( … , Instant.class ) ;
An Instant is always in UTC. Adjust into the time zone by which you want to perceive the date according to the wall-clock time used by the people of a certain region. For any given moment, the date varies around the world by zone. It might be “tomorrow” in Asia/Kolkata India while still “yesterday” in America/Montreal Canada.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Extract the date-only, as that is what you want to focus on.
LocalDate ld = zdt.toLocalDate() ;
Use the various plus/minus methods to add or subtract days, weeks, months, years, or a combination of those (Period).
LocalDate dayAfter = ld.plusDays( 1 ) ;
Or…
Period p = Period.parse( "P3M7D" ) ;
LocalDate later = ld.plus( p ) ;
For a database type akin to SQL-standard TIMESTAMP WITHOUT TIME ZONE, retrieve as a LocalDateTime. Skip the part above with time zone. Go directly to extracting the LocalDate. Proceed with your addition/subtraction.
myResultSet.getObject( … , LocalDateTime.class )
.toLocalDate()
.plusDays( 1 )
.toString()
To generate a String representing the date value in standard ISO 8601 format, call LocalDate::toString(). For other formats, use DateTimeFormatter. Search Stack Overflow to learn more.
sample:
Long timeStamp = 1466058808;
Time time = new Time(timeStamp );
DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(format.format(time));
print is: 2016-05-31 08:19:07
How can I get expected results is : 2016-05-31 00:00:00
Thanks!
And finally get the time stamp of 2016-05-31 00:00:00 This is what i want
So anyone know how to make it?
Simple, use:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
Or if you want a long (and have java 8):
LocalDateTime.ofEpochSecond(1466058808, 0, ZoneOffset.UTC).toLocalDate().atStartOfDay().toEpochSecond(ZoneOffset.UTC)
java.time
The Answer by krzyk is close but ignores the crucial issue of time zone. Let's try that again using the java.time framework built into Java 8 and later. Much of java.time functionality is back-ported to Java 6 & 7 (ThreeTen-Backport) and further adapted to Android (ThreeTenABP).
Count of seconds from epoch
You do not say so in the Question, but we assume the Long of 1466058808 is a number of whole seconds from the epoch of first moment of 1970 in UTC.
Instant
First we convert that to an Instant, a moment on the timeline in UTC.
Instant instant = Instant.ofEpochSecond( 1466058808L );
Time Zone
Determining a date, and the start of the day, depends on a time zone. For any given moment, the date can vary around the world by time zone. A few moments after midnight in Paris is still “yesterday” in Montréal.
ZonedDateTime
You can make wide use of Instant in your code. Generally best practice is to perform business logic, data storage, logging, and so on in UTC. Apply a time zone only where required such as display to a user. Apply a ZoneId to get a ZonedDateTime.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
Using LocalDate for start-of-day
To get the start of the day we need to go through the LocalDate class. Note that we should always pass the optional time zone argument. If omitted, the JVM’s current default time zone is implicitly applied. That default can change at any time, even during runtime, as any code in any app of the JVM can make a call to TimeZone.setDefault. Better to be specific.
LocalDate localDate = zdt.toLocalDate();
ZonedDateTime startOfDay = localDate.atStartOfDay( zoneId );
Note that you should not assume the day starts at 00:00:00.0. Daylight Saving Time (DST) may mean the day starts at a different wall-clock time.
One-liner
I do not recommend doing so, but you can combine all this into a single line.
ZonedDateTime startOfDay = ZonedDateTime.ofInstant( Instant.ofEpochSecond( 1466058808L ) , ZoneId.of( "America/Montreal" ) ).toLocalDate().atStartOfDay( ZoneId.of( "America/Montreal" ) );
use a Calendar, so you can extract date properties:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(millis);
//getting the desired properties
cal.get(Calendar.YEAR);
cal.get(Calendar.MONTH);
cal.get(Calendar.DAY_OF_MONTH);