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.
Related
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.
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).
I am using Eclipse (version: Kepler Service Release 1) with Prolog Development Tool (PDT) plug-in for Prolog development in Eclipse. Used these installation instructions: http://sewiki.iai.uni-bonn.de/research/pdt/docs/v0.x/download.
I am working with Multi-Agent IndiGolog (MIndiGolog) 0 (the preliminary prolog version of MIndiGolog). Downloaded from here: http://www.rfk.id.au/ramblings/research/thesis/. I want to use MIndiGolog because it represents time and duration of actions very nicely (I want to do temporal planning), and it supports planning for multiple agents (including concurrency).
MIndiGolog is a high-level programming language based on situation calculus. Everything in the language is exactly according to situation calculus. This however does not fit with the project I'm working on.
This other high-level programming language, Incremental Deterministic (Con)Golog (IndiGolog) (Download from here: http://sourceforge.net/p/indigolog/code/ci/master/tree/) (also made with Prolog), is also (loosly) based on situation calculus, but uses fluents in a very different way. It makes use of causes_val-predicates to denote which action changes which fluent in what way, and it does not include the situation in the fluent!
However, this is what the rest of the team actually wants. I need to rewrite MIndiGolog so that it is still an offline planner, with the nice representation of time and duration of actions, but with the causes_val predicate of IndiGolog to change the values of the fluents.
I find this extremely hard to do, as my knowledge in Prolog and of situation calculus only covers the basics, but they see me as the expert. I feel like I'm in over my head and could use all the help and/or advice I can get.
I already removed the situations from my fluents, made a planning domain with causes_val predicates, and tried to add IndiGolog code into MIndiGolog. But with no luck. Running the planner just returns "false." And I can make little sense of the trace, even when I use the GUI-tracer version of the SWI-Prolog debugger or when I try to place spy points as strategically as possible.
Thanks in advance,
Best, PJ
If you are still interested (sounds like you might not be): this isn't actually very hard.
If you look at Reiter's book, you will find that causes_vals are just effect axioms, while the fluents that mention the situation are usually successor-state-axioms. There is a deterministic way to convert from the former to the latter, and the correct interpretation of the causes_vals is done in the implementation of regression. This is always the same, and you can just copy that part of Prolog code from indiGolog to your flavor.
I was reading the scala doc for the scala.concurrent.duration.Duration class, and I just discovered that it starts with:
This class is not meant as a general purpose representation of time, it is optimized for the needs of scala.concurrent.
Why are the implications of this statement? What's a better alternative?
I guess I'm partially responsible for this.
The general issue here is that time system are hard. Really, really, really hard.
The Akka developers who worked on standardizing Futures needed a construct to describe the length between two “anonymous” points in time to implement their functionality. Duration was built to solve this specific requirement.
My concern was that people might start using this time-related class for things it wasn't designed for bringing us into a troublesome situation comparable to java.util.Date/java.util.Calendar (not quite because Duration actually works for its use-case) where tons of people would misuse it as some kind of scala.time which it was never intended to be.
That's why it has this note and is packaged into scala.concurrent.duration instead of e. g. scala.time.
I look forward to the java.time package shipping with Java 8. It might be possible to standardize on that in the future which would improve interoperability a bit and would have the additional benefit of being designed for a much broader use-case. (It will probably take a long time until Scala uses Java 8 as a baseline, though...)
Time can be represented in various ways depending on your needs. I personally have used:
Long — a lot of tools take it directly
Updated: java.time.* thanks to #Vladimir Matveev
The package is designed by the author of Joda Time (Stephen Colebourne). He says it is designed better.
Joda Time
java.util.Date
Separate hierarchy of classes:
trait Time
case class ExactTime(timeMs:Long) extends Time
case object Now extends Time
case object ASAP extends Time
case class RelativeTime(origin:Time, deltaMs:Long) extends Time
Ordered time representation:
case class History[T](events:List[T])
Model time. Once I had a global object Timer with var currentTime:Long:
object Timer {
private var currentTimeValue:Long
def currentTimeMs = currentTimeValue
def currentTimeMs_=(newTime:Long) { ... some checks and notifications}
def pseudoRandom:Double = ...
}
And everywhere in the program I called Timer.currentTimeMs to get the time. It allows to write deterministic tests with controlled time shift. (Beware of global variable! Now I prefer to use separate instances of Timer to avoid concurrency issues.)
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.