Date is deprecated. Should I use it or not? - date

Date has many deprecated methods, i.e, getTime, getMounth, etc. Should I avoid using it?
Also, what is the difference between: Date, Calendarand DataPicker?

Date was deprecated in the JDK v1.1; in other words relatively early during the (ongoing) development of the environment. It was deprecated because of incompatibility with international time standards; while it was intended to reflect coordinated universal time (UTC) it was found that on machines that use the GMT time standard or those that do not reflect a "leap second" (an extra second once every year or two) that the Date class might not be exactly accurate.
For this reason, it is recommended that you use Calendar.get(...) instead of Date's respective methods! Also, Java8 has a UI component, DatePicker, which use's the new LocalDate class (which is a localized replacement for the deprecated Date class).

Related

Kotlin - Unparseable date: "2021-07-20T12:35:07-07:00"

I'm getting an unparseable date exception using:
"2021-07-20T12:35:20-07:00".toDate()!!
#SuppressLint("SimpleDateFormat")
fun String.toDate() : Date? {
return SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(this)
}
From the SimpleDateFormat docs
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00
The Z directive expects the time zone to be specified without a colon, whereas X allows a colon. Either format your dates like
2021-07-20T12:35:20-0700
or use the ISO 8601 timezone designator, rather than the RFC 822 one
yyyy-MM-dd'T'HH:mm:ssX
Try it online!
java.time through desugaring
I recommend that you uses java.time, the modern Java date and time API, for your date and time work. Excuse my Java syntax:
public static OffsetDateTime toDate(String s) {
return OffsetDateTime.parse(s);
}
Let’s try it:
OffsetDateTime dateTime = toDate("2021-07-20T12:35:20-07:00");
System.out.println(dateTime);
Output is:
2021-07-20T12:35:20-07:00
We do not need to specify any formatter at all. Your string is in ISO 8601 format. OffsetDateTime and the other classes of java.time parse the most common variants of ISO 8601 as their default, that is, without any explicit formatter. Which is good because as you experienced, constructing a formatter is error-prone.
In case you need a Date object for an old API not yet upgraded to Java time, the conversion is:
Date oldfashionedDate = Date.from(dateTime.toInstant());
System.out.println(oldfashionedDate);
Output (from a device in Europe/Brussels time zone):
Tue Jul 20 21:35:20 CEST 2021
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
Java 8+ APIs available through desugaring
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Wikipedia article: ISO 8601

get Current Date in Scala without java class

Is there any way to get the current date in Scala without using Java class import java.text.SimpleDateFormat and import java.util.Date?
java.time
You should not be importing java.text.SimpleDateFormat or java.util.Date. Those troublesome old classes are now legacy, supplanted by the java.time classes.
While I do not know Scala syntax, here is Java syntax.
java.time.Instant.now() // Current moment in UTC, with a resolution of nanoseconds.
…and…
java.time.ZonedDateTime.now( ZoneId.of( "Africa/Tunis" ) ) // Current moment adjusted to the wall-clock time as used by the people in a particular region (time zone).
…and…
java.time.LocalDate.now( ZoneId.of( "Pacific/Auckland" ) ) // Current date (date-only, no time-of-day nor zone) of the people in a particular region (time zone).
http://pavkin.ru/cross-platform-polymorphic-datetime-values-in-scala-with-type-classes/
The Goal
There’s no solution without a goal. Precise goal will also provide correct context for reasonings in this article. So let me state it.
My primary goal is to be able to write cross-platform code that operates on date/time values with full time zone support.
This also means that I will need implementation(s) that behave consistently across JVM and browser. We’re Scala programmers, so let’s choose JVM behaviour semantics as our second goal.
Options explored in the article are
https://github.com/scala-js/scala-js-java-time
This library is the future of cross-platform date/time code. It’s effectively Java 8 time, written from scratch for ScalaJS.
At the time of writing this post, scala-js-java-time already provides LocalTime, LocalDate, Duration , and a handful of other really useful java.time.* classes (full list here).
https://github.com/soc/scala-java-time
Scala Java-Time is a fork of ThreeTen backport project. So it’s main purpose is to provide java.time.* -like functionality on Java 6 & 7.
It is also compiled to ScalaJS, which means we can write cross-platform code with it. And we can even use (to some extent) LocalDateTime!
https://github.com/mdedetrich/soda-time
Soda time is a port of Joda to ScalaJS.
It’s in early development stages and also doesn’t have time zones in ScalaJS, but I still added it to the list, because developers took an interesting approach: they are converting original Joda code with ScalaGen.
The author then goes to recommend that at the time of writing the article, (Published 11.11.2016)
There’s no cross-platform library with full time zone support. And for JavaScript runtime there’s only MomentJS, that really fits our requirements.
So unless one of those have evolved, or you only need a subset of datetime functions, or another solution has raised it's head, you are probably stuck implementing some sort of interface over the behavior needed, and swapping it out based on whether you are on java or scalajs.
Well, it's unclear - beside the hint about newer classes mentioned by Basil - why you would do this, need this.
On unix-like systems you can use the System date, probably on Windows systems too, but with the same syntax? You probably loose system independency:
scala> import sys.process._
import sys.process._
scala> "date".!
Mi 31. Jan 07:09:04 CET 2018
res150: Int = 0
If you have a database, these often provide the date/time too.
Then you could try to get the date via TCP/IP.
All this solutions are in allmost all cases inferior to using the newer Java classes and even the older ones.

Java 8 Date API vs Calendar / Date / DateFormat

There is this new-n-cool Date API in Java 8, the java.time package. I understand that it is better designed, less ambiguous and more thread-safe than the old classes. Still, I am not sure how to go about using it:
Should I use it exclusively instead of the old classes?
Should I replace existing usages of old classes whereever I spot them because the new stuff is so much better?
Should I refrain from using java.util.Calendar, java.util.Date, java.sql.Date and java.text.DateFormat in favor of the new API all together OR are there use cases where the old classes are still preferable?
Has the Joda Time API become obsolete thanks to the new Date API similarly to the substitution of Guava FluentIterable by Java 8 stream API?
I know these are a lot of questions, but they feel somewhat related to each other. If somebody can answer the whole bunch, that would be awesome, but good partial answers are also appreciated.
Should I use it exclusively instead of the old classes?
No, no need to exclude old classes. The old java.util.Date/.Calendar work the same, unchanged. The have not been deprecated.
You can mix and match all three frameworks (old classes, Joda-Time, and java.time). Just be careful of some identical or similar class names -- watch your import statements!
See The Tutorial, Legacy Date-Time Code.
Also, the ThreeTen-Extra project extends java.time with additional features. The "ThreeTen" refers to JSR 310 that defines java.time.
Should I replace existing usages of old classes whereever I spot them because the new stuff is so much better?
If the old code is working as intended, then no need to change now.
If you were concerned about that old code possibly not handling time zones properly or have been wanting to do more localization, the you might want to rework them using java.time. Even then, remember that you can easily convert between j.u.Date and Instant. So you could leave your business logic as-is with j.u.Date/.Calendar and change only the user-presentation code to use java.time.
Should I refrain from using java.util.Calendar, java.util.Date, java.sql.Date and java.text.DateFormat in favor of the new API all together OR are there use cases where the old classes are still preferable?
You will need the old classes for interoperation with old code and libraries that expect the old types. Again, the old classes are not deprecated and are not going away. They will probably never go away given their extensive usage and the Java team’s top priority being preservation of backward-compatibility.
The new java.time classes are far superior, that's why they were added. And they are more logical and easier to use. So yes, it would be beneficial and pleasant to learn how to use them. But not urgent. In a crunch, write code the old way you are used to. When you can afford the time to learn (Tutorial) and to perform extra testing, start to use the new classes.
A newbie programmer should certainly focus their learning on java.time.
Has the Joda Time API become obsolete thanks to the new Date API similarly to the substitution of Guava FluentIterable by Java 8 stream API?
Joda-Time was the inspiration for java.time. The same folks invented both. They intend for java.time to be their "2.0" re-invention of Joda-Time, what they would have done then if they knew what they know now. They have said Joda-Time users should transition over to java.time.
That said, Joda-Time is not going away. It is still worked on, still updated with bug fixes and fresh tz time zone data. And it is very important to the large Android community who have no other decent date-time library (that I know of). So you can continue to rely on Joda-Time, no urgent need to rip out old code, but expect no new features or enhancements.
Joda-Time is well-worn and proven while java.time has had a few minor bugs and kinks to work out. Joda-Time and java.time each have features the other lacks. So personally, I mix-and-match to best fit. I rely on Joda-Time while dabbling with java.time.
Plan an eventual transition to java.time but no rush, no panic.

How to replace Date object

Date date = new Date();
int lastMonth = date.getMonth();
int lastYear = 1900 + date.getYear();
I have this code in my GWT project but a lot of method of java.util.Date is deprecated, 22/33 methods.
So I want to use Calendar/GregorianCalendar : it does not work. It said there is a missing package.
What is the best practice to replace these line of code with a not deprecated code ?
Don't.
java.util.Calendar is almost impossible to emulate, and has a way too high overhead. java.util.Date, while far from ideal, is the closest to JavaScript's Date, so it's the one you should use in GWT world.
JSR 310 is promising (don't know how well it could be emulated though, and with how much overhead compared to java.util.Date) but isn't there yet.
There's also Joda Time (from the same author as JSR 310, JSR 310 aims at bringing Joda Time to the JDK along with fixing some of its early design mistakes), but most GWT ports have long been abandonned.
In the end: use java.util.Date.
And if you find the deprecation warnings annoying, then suppress them: #SuppressWarnings("deprecated").
java.util.Date is not deprecated! Admittedly many methods of it are (like getMonth and getYear) which I try to avoid using. In the case of GWT you can use something like DateTimeFormat to do date formatting and parsing.

How to convert an NSTimeInterval into an date with time?

I have an NSTimeInterval value, or more precisely an NSTimeInterval "since reference date". I think that's a value in seconds from 1970 or something like so. Pretty standard in most programming languages, I think.
So now I have that ugly value which the user doesn't understand, and I'd like to display a date + time. Is there a useful method or function that would do that, maybe by specifying formats or a locale as well? Maybe the iphone also has built-in support for this kind of stuff so that the date+time is displayed automatically like the user likes it in his/her settings?
You want to create an NSDate with +[NSDate dateWithTimeIntervalSince1970:]. You can then get the date's -descriptionWithLocale: or use the Date and Time Programming Guide from the iPhone library to find out more options for displaying the date.